Extension Methods

Extension Methods are a nice way to add some extra functionality to a already existing class.
I use them for several tasks which are needed quite often. Such as the “raising” of an event or just the running of an action in the correct thread.
Therefore I decided to post the most important Extension Methods here.

When “raising” (fire) an event it is really annoying that we always have to check if the event is not null.
This results in a quite long code and we have always to repeat the same thing again.

Example:

public event EventHandler<EventArgs> MyEvent;

protected void RaiseMyEvent()
{
   if(MyEvent != null)
      MyEvent(this, EventArgs.Empty);
}

Using this extension method

/// <summary>
/// This method raises the given event with the given sender and EventArgs
/// </summary>
/// <typeparam name="T">The type of the event handler</typeparam>
/// <param name="eventHandler">The event handler</param>
/// <param name="sender">The sender</param>
/// <param name="e">The event args</param>
public static void Raise<T>(this EventHandler<T> eventHandler, Object sender, T e) where T : EventArgs
{
	if (eventHandler != null)
	{
		eventHandler(sender, e);
	}
}

it is possible to raise the event with that

public event EventHandler MyEvent<EventArgs>;

MyEvent.Raise(this, EventArgs.Empty);

Another example where Extension Methods are really useful is when you want to ensure that an action / function is executed in the right thread.
Usually you have to check whether you actually are in the right thread and invoke if necessary.

example:

public void MyMethod()
{
     if(myDispatcher.CheckAccess())
     {
        DoSomething();
     }
     else
     {
        myDispatcher.Invoke(new Action(MyMethod));
     }
}

In order to reduce this “useless” code we can use the following extension method

		/// <summary>
		/// This method automatically executes the given action in
		/// the correct thread.
		/// </summary>
		/// <param name="source">The source of the method call</param>
		/// <param name="func">The function which should be executed in the right thread</param>
		public static void Dispatch(this Dispatcher source, Action func)
		{
			if (source.CheckAccess())
				func();
			else
				source.Invoke(func);
		}

And here an example how to call it

myDispatcher.Dispatch(DoSomething);

More useful extension methods will follow…

Advertisements
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: