Thursday, 25 August 2011

What is Lambda Expression? A simple guide For beginners

Whenever we talk about LINQ then everything related to LINQ comes as a part of discussion and so the Lambda Expressions are. Sometimes people ask the question about the Lambda Expression; It look so weird why should I use it in my code and what exactly it stands for? Developers who either from C++ or working on C# 2.0 are still not have clear vision of Lambda Expression. What are Lambda Expressions?, When & Where to use them? These are the basic question that can comes in mind when anybody heard of new programming things.
Through this post I'll try to answer these question. There are new terms are being introduced with every release of .Net framework so lets get started with Lambda Expression for now:

What is Lambda Expression?
Lambda expressions are similar to anonymous methods introduced in C# 2.0, except that lambda expressions are more concise and more flexible. All lambda expressions use the lambda operator =>, which is read as “goes to”. The left side of the lambda operator specifies the input parameters and the right side holds the expression or statement block.

Lets take an example:
delegate int anonymousDel(int i);
            anonymousDel myDelegate = new anonymousDel(
            delegate(int x)
            {
                return x * 2;
            });

            Console.WriteLine("{0}", myDelegate(5));

The segment inside the braces of anonymousDel is the also called as Anonymous Function.
Now lets convert it to Lambda Expression:
anonymousDel myDelegate = x => x * 2;

x => x * 2 is the Expression that is known as Lambda Expression. All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * 2 is read "x goes to 2 times x." This reduced the no. of line as you can see and the output is still the same.

The above expression can be generalize for clear understanding.
(input parameters) => Expression;
and can be termed as "Expression Lambdas" since single Expression is involved here.
A Lambda Expression can contain multiple statements and can be surrounded by { } just like anonymous functions.
(input param1, input param2) => { statement1, Statement 2};
For e.g.
anonymousDel2 getBigInteger = (x, y) => { if (x > y) return x; else return y; };
Console.WriteLine(getBigInteger(10,15));

You can raise a question here how x & y are being treated as integer while you didn't declared them as integer?
Here is the answer, When writing lambdas, you often do not have to specify a type for the input parameters because the compiler can infer the type based on the lambda body, the underlying delegate type, and other factors as described in the C# Language Specification.
Anonymous function that take no parameter and return nothing can be written in form of Lambda Expression like below:

delegate void doSomething();
           
doSomething IamVoid = () => { Console.WriteLine("Hello there! I take nothing and return nothing"
); };
           
//call the Anonymous function
            IamVoid();

When & Where to use Lambda Expression?
Whenever you came to know about new term and you already know what it is then directly ask yourself when & where it would be used. The Lambda Expressions can be used to  simply replacing the Anonymous functions, In the LINQ query methods, or any where you need to intialize Generic delegates.
LINQ Query example:

LINQ to Objects

int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
           
int oddNumbers = numbers.Count(n => n % 2 == 1);

LINQ to SQL
Customers.Where(c => c.City == "London");

LINQ To XML
var xml1 = element.Descendants("customer").Where(cust => cust.Attribute("id").Value == CustomerId).SingleOrDefault();

OTHER
Func<>, Action<> and Expression<> are the new generic delgates where you can use Lambda Expressions. Don't panic with these new terms Lets take example where are these new generic delegates can be used.

Look at the below code snippet:

delegate int anonymousDel2(int a, int b);
anonymousDel2 getBigInteger = (x, y) => { if (x > y) return x; else return y; };
Console.WriteLine(getBigInteger(10,15));

Lets modify the above code snippet using generic delegates and Lambda Expressions
Func<int, int, int> getBigInteger = (x, y) => { if (x > y) return x; else return y; };
           
Console.WriteLine(getBigInteger(10,15));

Explanation of Func<int, int, int> would be Func<parameter1, parameter2, returntype>
you can pass any number of argument but last mentioned type would be the type of returned value. Similary we use Action<param1, param2> in this we don't need to return any value. It denotes the Generic delegate here that have return type void. These delegates are introduced to provide the taste of Functional Progamming in the C# itself. if you are still interested in further reading then its worth for me writing this post.

When to use Lambda Expression?
Use whenever you feel reducing your line of code. Keep in mind the code maintainability while reducing the number of code lines. People think Lambda Expression as awkward looking code, But I'm telling you its worth using them in code wisely and once you understood the concept you'll fall in love using them. If you are going to use Excess of LINQ in your code then Lambda Expression will be your favorite buddy helping you wrap your code logic in few lines or may be Inline.

Hope you enjoyed reading this. Thanks for you time please leave comment for any question/suggestion.