Generic EventArgs

This has been done before but I think this is a cool tip that can save a heap of time and reduce the number of classes in your app.

There are a lot of times when you want to raise a quick event and just simply pass an value type or object as part of the EventArgs parameter. Instead of having to create separate EventArgs for every event you want to raise, we can create an EventArgs class that uses generics.


    public class EventArgs : EventArgs
    {
        public EventArgs(T value)
        {
            Value = value;
        }

        public T Value { get; set; }
    }

Usage:

    public event EventHandler<EventArgs<int>> SomeEventWithIntArg;

...

    if (SomeEventWithIntArg != null)
    {
        SomeEventWithIntArg(this, new EventArgs<int>(123));
    }

You can wire up the SomeIntEvent event and I will be able to access eventArgs.Value


    SomeEventWithIntArg += OnSomeEventWithIntArg;


    void OnSomeEventWithIntArg(object sender, EventArgs<int> eArgs)
    {
        int i = eArgs.Value;
    }

No comments:

Post a Comment