Misiu
Misiu

Reputation: 4919

Generic EventArgs and extension method

I was looking over the internet for a way to fire events easier and I found this extension class:

public static class EventExtensions
{
    public static void Fire<TEventArgs>(this EventHandler<TEventArgs> @event, object sender, TEventArgs e)
        where TEventArgs : EventArgs
    {
        if (@event != null)
            @event(sender, e);
    }
}

This allows me to fire event using

TestEvent.Fire(this,new CallEventArgs(1,"OK"));

instead of

if(TestEvent != null)
    TestEvent(this, new CallEventArgs(1,"OK"));

Because I need to pass some arguments to my events I thought I will create generic EventArgs class:

public class EventArgs<T> : EventArgs
{
    public EventArgs()
    {
        Value = default(T);
    }

    public EventArgs(T aValue)
    {
        Value = aValue;
    }

    public T Value { get; set; }
}

With this I can declare my event as:

public event EventHandler<EventArgs<MyClass>> TestEvent; 

and fire it with:

if(TestEvent != null)
    TestEvent(this, new EventArgs<MyClass>(new MyClass{Id = 1, Description = "OK"}));

My questions are:

1.How should I modify my extension method to be able to call my event as below?

TestEvent.Fire(...);

2.Is it good practise to extend events and then write extension methods to them this way?

Upvotes: 2

Views: 841

Answers (1)

Athari
Athari

Reputation: 34285

  1. You don't need to modify anything, your extension method should work fine with generic EventArgs<T>.

  2. This approach is fine, there's nothing wrong about it.

  3. You may want to add the following overload:

    public static void Fire<T> (this EventHandler<EventArgs<T>> @event, object sender, T value)
    {
        if (@event != null)
            @event(sender, new EventArgs<T>(value));
    }
    

    This way, you'll be able to fire events like this:

    TestEvent.Fire(sender, new MyClass{Id = 1, Description = "OK"});
    

Upvotes: 3

Related Questions