Concise your code with lambda's.
The new feature which is extensiely used by LINQ in C#3.0 is Lambda expressions.
It gives very stinct syntax for the developer to write the code.
Lambdas are simply shorthands for creating a delegate and pointing it to a method. Apart from
this, they offer type inference.
Consider the following C# example:
delegate bool SimpleDelegate(int i);
public void SimpleMethod()
{
SimpleDelegate sd = new SimpleDelegate(SomeMethod);//simple way
sd(5)//calling the method with delegate
Console.WriteLine(res.ToString());
}
private bool SomeMethod(int i)
{
return i > 2;
}
Here Nothing complicated (or useful) takes place.
Now Before rewriting it using a lambda expression, let's re-write it a bit using C# 2.0 anonymous methods that we know.
delegate bool SimpleDelegate(int i);
private void SimpleMethod()
{
SimpleDelegate sd = delegate(int i){return i > 2;} ;//using Anonymous delegate with parameters.
bool result = sd(5);
Console.WriteLine(result.ToString());
}
with the use of anonymous methods, basically we have inlined SomeMethod by using the delegate keyword.
with Lambda expressions actually we can take this to the next level of conciseness.
So the above line:
delegate(int i){return i > 2;}
can be written like this:
(int i) => { return i > 2;}
So here simply replacing the delegate keyword with the syntax =>
Hence the code looks like
private void SimpleMethod()
{
SimpleDelegate sd = (int i) => { return i > 2;}//using lambda expression.
bool result = sd(5);
Console.WriteLine(result.ToString());
}
However the beauty is that, since the body only has a single return statement, we can make the above syntax even more concise.
And here the compiler infer the parameter type: .i.e it treats i as integer. no need of mentioning int explicitly .
So the as follows.
SimpleDelegate sd = i => i > 2;
So the above method can be rewritten as
private void SimpleMethod()
{
SimpleDelegate sd = i => i > 2;//Even more concise.
bool result = sd(5);
Console.WriteLine(result.ToString());
}
And that is the basics of lambdas: it looks weird, it is concise and it does some inference for us.
Happy coding.. :)