Generic Delegates and Lambda Expressions

19 01 2008

.NET 3.5 now provides Generic Delegates which can be used in place of Anonymous Methods

The Generic delegates always encapsulate a method which can accept 1 or more inputs and return a value. So, currently we have,

1) Func<TResult>

2) Func<T,TResult>

3) Func<T1,T2,TResult>

4) Func<T1,T2,T3,TResult>

5) Func<T1,T2,T3,T4,TResult>

Well enough to cater our needs 😉

Lets take an example

Problem: Given an array of words, and a desired length, return me all the words which satisfy that length

Let me give the solution straight away,


As you can see we have used the Func<T1,T2,TResult> generic delegate where our first parameter is an array of strings and the second parameter is an integer and third parameter which is the return type is ArrayList

If you look closely, we have also used the Lambda operator too in building the function 😉

Now, let us fire our Reflector and see what is there

reflector-function-delegates.jpg this has been transformed into an Anonymous Method and the delegate is nothing but our Func<T1,T2,TResult>

Lets again take a look at how Func<T1,T2,TResult> is declared,

public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);

Well, I think that explains it 😉

So, what about directly using Lambda expressions..mmm…like this,


That does reduce our lines of code and the way we interpret things 😀 . I feel the above method is lot more easier than our generic function delegates. So what does our Reflector say about this,


So what is that CS$<>9__CachedAnonymousMethodDelegate2

My Reflector says it is nothing but,


private static
     Func<string, bool> CS$<>9__CachedAnonymousMethodDelegate2;

So, again we are back to our generic delegates 8)

Yes, so as we can see it transforms the lambda expressions into delegates 😀

From MSDN,

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

I think that explains our Reflector was indeed correct 8)