Monday, July 28, 2008

Writing Anonymous Methods with Lambda Expressions

I like using Lambda expressions for anonymous methods. I don't really have a good reason for it, but I like it, so here's the difference. Let's say you have a class exposing the following delegate:

public delegate bool CheckExpirationDelegate();
public CheckExpirationDelegate CheckExpiration;



The normal anonymous delegate would look like this:
di.CheckExpiration += delegate() { return true; };


But, you can also do it like this with lambda expressions:
di.CheckExpiration += () => true;




Here's another anonymous method, but you can use this one without a delegate:
Func<string, char, string> GreetTheWorld =
    (greeting, punctuation) =>
        string.Format("{0} World{1}", greeting, punctuation);
    Console.WriteLine(GreetTheWorld("Hello", "!"));




There are many other great uses for lambda expressions . . . fodder for future posts.


© 2008, D. Patrick Caldwell, Vice President for Research and Development, Emerald Software Group, LLC

No comments:

Post a Comment