Tuesday, 16 October 2012

Basics: Understanding Lambda Expression

If you are following my blog, I have been writing posts on latest technologies, concepts and some of the issues that I faced with their solutions. I decided to put some posts on basic some concepts intermittently. This is the first post of the never-ending basics series.

I often hear from people that lambda expression does a magic behind the scenes which is hard to understand. I agree that it works magically, but the magic is not hard to understand. When I saw lambda expression for the first time, one of my friends told me that it is a delegate. Then I tried to understand how it is a delegate and how does it work behind the scenes.

With my understanding of creating delegates with anonymous methods, I thought that when we write a lambda expression, we are defining an anonymous method and assigning it to a delegate object without using .NET’s delegate keyword.

Keeping the above point in mind, I started writing a small Console Application to move from a delegate with a named method attached to it to lambda expression. I wrote a method that checks if a number is positive and returns a Boolean value and declared a delegate to hold methods of similar signature:
delegate bool PositiveTest(int number);
bool CheckIfPositive(int number)
{
    return number > 0;
}

Step 1: Instantiating and invoking the delegate using a defined method:
PositiveTest testDelegate = new PositiveTest(CheckIfPositive);

Step 2: Instantiating delegate using anonymous method and the delegate keyword:
PositiveTest testAnonymousDelegate = delegate(int number)
{
    return number > 0;
};

Step 3: Removing the delegate keyword and introducing =>:
PositiveTest delegateWithoutDelegateKeyword = (int number) =>
{
    return number > 0;
};

Step 4: Removing data type of the input parameter:
PositiveTest delegateWithDataTypeRemoved = number =>
{
    return number > 0;
};

Step 5: Removing curly braces and the return keyword:
PositiveTest delegateWithNoBracedNReturn = number => number > 0;

In the above listing, the amount of code written to instantiate a single cast delegate is gradually reduced. We moved from delegate accepting a defined method to delegate accepting an expression that doesn’t have types or curly braces. I hope, now you feel comfortable with lambda expression if you had any confusion earlier.

Happy coding!

No comments:

Post a Comment