Geeks With Blogs
New Things I Learned

In the way distant past, I ended up creating a new delegate for just about each function I need represented as a delegate.  And as I experienced an explosion of delegates and needing to come up with the names for it, I ended up creating 2 sets of delegates as follows:


public delegate void VoidFunction();

public delegate void VoidFunction<T>(T argument1);

public delegate void VoidFunction<T, U>(T argument1, U argument2);


public delegate R Function<R>();

public delegate R Function<R, T>(T argument1);

public delegate R Function<R, T, U>(T argument1, U argument2);

My code will use the VoidFunction delegate to represent methods that doesn't return anything (void).  And I'll use the other one that needs return value - the type inference in .NET is nice since it strong types return values as well.  I also overload to 2 only since those are the ones I use most - I found that if I need one with more arguments, I'd better off creating a new delegate altogether since naming those delegates properly help in reading code.

With .NET 3.5, to support LINQ, Microsoft has created these same delegates set, but with more overloads so it can accept more parameters.  The delegates that return void are named Action, and the delegates that supply a return value are named Func.  Each has generic overloads to accept up to 4 parameters.  More information can be found here - you need to scroll all the way down to where you can see the list of delegates - there you'll see the Action delegates and the Func delegates.

A couple of snags:

  • Since the delegates are defined in .NET 3.5, that means that you need the 3.5 framework installed and your app need to also target the 3.5 framework.
  • The Func delegates put the return value last - in terms of usage, it doesn't matter since .NET will resolve it - but I'm finding this pattern a bit against their typical pattern of keeping the order of things the same.  Which is why in my implementation, I keep the return value type parameter as the first type.

I'm also suprised that Microsoft only started doing these now, instead of say since .NET 2.0, or even 3.0.  The only delegate that was created before (as early as 2.0 actually) was the Action<T> - since it is used for one of the method in List<T>, the ForEach method in particular.

Posted on Friday, February 8, 2008 12:19 PM .NET | Back to top

Comments on this post: New delegates in .NET Framework 3.5

# re: New delegates in .NET Framework 3.5
Requesting Gravatar...
update me..
Left by ALI KAMAL on Feb 09, 2008 1:42 AM

Your comment:
 (will show your gravatar)

Copyright © Muljadi Budiman | Powered by: