Reputation: 4919
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
Reputation: 34285
You don't need to modify anything, your extension method should work fine with generic EventArgs<T>
.
This approach is fine, there's nothing wrong about it.
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