Useful EventArgs utility class

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!


About programabilan

Profesionalni programer, amaterski programer...

Posted on November 18, 2011, in Tips and tagged . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: