Lambdas and Generic Delegates

It took me a century to figure out lambdas and what they are all about. So, as I was thinking about what to blog about next I thought I’d share about the moment that lambdas and me clicked.

When I looked at lambdas as shorthand for anonymous delegates and expressions, I came up with a phrase to help me visualize what’s going on. When I read a lambda I say, “with value of variable return expression.” A Predicate delegate would be expressed as a lambda as x => x == 1 would read, “with value of x return x is equal to 1.” When I made => read as return, I stopped trying to force it into some kind of comparison operator (if you have code dyslexia like me, you know what I’m talking about).

Another way to look at it is in terms of what’is happening under the hood. A lambda is like shorthand for anonymous delegates. In longhand, full declaration, as an anonymous delegate, the above lambda would be,

delegate(int x){return x == 1;}

Generic Delegates

Since I mentioned anonymous delegates, I should giving a passing shout out to Generic Delegates.  I use most often:

Predicate must return true or false. Can accept only one parameter.

Func returns the value specified in the parameter. Can accept 4 parameters in .net 3.5 and 16 in 4.0.

Action would not return a value. Can accept 4 parameters in .net 3.5 and 9 in 4.0.

Comparison returns a signed int indicating the result of comparison. If the returned int is

< 0 then x < y
= 0 then x = y
> 0 then x > y

The Comparison delegate can accept two objects of the same type that will be compared (x and y).

Converter returns the result of an object conversion operation. Can accept one input object (to be converted) and an output (return) object (is the converted input object).

EventHandler returns void. Accepts a System.Object (source of event) and TEventArgs (the event’s data).

Anyway, delegates are a powerful feature of C# that I am guilty of not taking advantage of like I should. Hopefully, doing this little post will help in grain them more into my solution designs. If you haven’t been exposed to or currently using Generic Delegates or Lambda Expressions, I challenge you to see how they can help solve some of your problems in a more abstract, efficient and maintainable way. Try them out you may discover a new way to think about and write code.

Leave a Reply

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

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