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)




One response

7 03 2010
Ralph Oteon

This might be a weird question, but I’m a vegetarian, and am trying to find contact lenses that don’t have some animal suffering. I gather that many lenses contain either ingredients which are tested on rabbits, or are manufactured from animal products. Are there lens brands which are entirely artificial?

Leave a Reply to Ralph Oteon Cancel reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: