Hi,
One of the good uses of extension method that one of my friends told me when in discussion was to also reduce the code, by using extension method in the right place.
The first example we came into was firing of an event. When we need to fire an event we always need to make a check if the Event is null or not. Only in case when event is null (meaning there is at least one function pointer attached) we raise the event.
But this checking for null can be easily made generic with the help of an extension method. We can easily create an extension method on the class EventHandler. After that all we need to do is calling the new extension to raise the event and that will take care of checking for the null. Here is the code for the same
public static void RaiseEvent<TEventArguments>(
this EventHandler<TEventArguments> EventName,
object sender, TEventArguments e)
where TEventArguments : EventArgs
{
if (EventName != null)
{
EventName(sender, e);
}
}
That’s all and this can help us in not writing the same piece of code again and agin at multiple places.
Vikram