Hi,
Raising EventHandlers is a repetitive task in .NET Development. But this can be improved with C# 3 Feature with Extension Methods.
Actually you need to do the following :
public event EventHandler<EventArgs> MyEventHandler;
public void DoSomething()
{
var e = MyEventHandler;
if(e != null)
{
e(this, new EventArgs());
}
}
In order to avoid this repetitive Task, my friend Brian on this blog post talked about a useful Extension Method.
Generic EventArgs EventHandler
public static void Raise<TEventArgs>(this EventHandler<TEventArgs> eventHandler, Object sender, TEventArgs args)
{
var e = eventHandler;
if (e != null)
{
e(sender, args);
}
}
However he didn’t provide a standard EventHandler EventArgs-less Implementation of the Extension Method.
Here is the Code.
Standard EventHandler
public static void Raise(this EventHandler eventHandler, Object sender)
{
var e = eventHandler;
if (e != null)
{
e(sender, null);
}
}
Hope this help’s!
Views(1903)

