Although there is a generic version for EventHandler delegate available in .NET Framework: EventHandler<TEventArgs>, it requires that generic argument derives from EventArgs. For very simplistic scenarios where you want to send simple data such as string or a number, creating a new class for the event argument is little too much work.
Fortunately, you can use this small class that will provide the necessary signature for event arguments.
public class EventArgs<T> : EventArgs
{
public T Value { get; private set; }
public EventArgs(T val)
{
Value = val;
}
}
You can use it to create event handlers easily:
public event EventHandler<EventArgs<string>> StringReceivedEvent;
public void OnStringReceived()
{
if (StringReceivedEvent != null)
StringReceivedEvent(this, new EventArgs<string>(somestring));
}
// client code
StringReceivedEvent += (o, e) => Console.WriteLine(e.Value);
Happy coding!
Last updated by at .
Back to top