Google
WWW Yariv Hammer's Code Site

Monday, September 04, 2006

Creating a general delegate using Generics

Introduction
I recently worked on a heavy UI application, with a client and a server. The thing that I encountered is that I often tried to access the UI from the thread of the remoting instead of the thread of the GUI. Of course I recieved an exception for that, because you must handle all the controls and graphics from the GUI thread.

This made me program a lot of code like this:
------------------------------------------------------
if (myControl.InvokeRequired)
myControl.Invoke(new SomeDelegate(SomeUIMethod),new object[] {parameterToPass});
else
SomeUIMethod(parameterToPass);
------------------------------------------------------
Of course I had to create both the method that handles the UI, and the delegate that accept the exact same parameters as the method.

This created a very messy code. The above code appeared in many places, and I had to create many small methods to handle small operations in the UI, and a delegate fro each method.

A Solution
A very pretty solution was suggested to me by wildfrog in CodeGuru (here), and I must put it in my blog.
He suggested to use generics in order to eliminate the need to use delegates for each method.
Here is his solution:
---------------------------------------------------------
public delegate void GeneralDelegate();
public delegate void GeneralDelegate<T1>(T1 t1);
public delegate R GeneralDelegate<R, T1>(T1 t1);

public delegate R GeneralDelegate<R, T1, T2>(T1 t1, T2 t2);
---------------------------------------------------------
And so on you can continue to create overloads for the delegate. You must create different delegates if you need to use void as return value. And the compiler will shout at you if you do not declare an appropriate delegate.

In order to use this GeneralDelegate, I write for example:
--------------------------------------------------------
public char test(bool b, int i)
{
return 'c';
}

new GeneralDelegate<char, bool, int>(test);
---------------------------------------------------------

This is absolutely great, and saves me a lot of coding.
I must emphasize that I only use this when I need to invoke a small method, and I do not use this in all the places I need a delegate (in fact I try to use this as little as possible, just when I feel that putting the typed delegate seems unnecessary).

0 Comments:

Post a Comment

<< Home

Feel free to use everything here. Add links to my site if you wish.

Do not copy anything to other sites without adding link to here.

All the contents of the site belong to Yariv Hammer.