Today, quite a simple topic, we will start with lambda expressions, these are unnamed methods used together with delegates.
Lambda expressions
Example of lambda expression:
delegate int LambdaTest(int i);
static void Main(string[] args)
{
LambdaTest sqr = x => x * x;
Console.WriteLine(sqr(10)); // 100
Console.ReadKey();
}
The general form of the lambda expression looks like this:
(parameters) => instruction block
You can leave the bracket when there is only one argument in the expression in our example, that is, x in the lambda expression corresponds to the parameter i in the delegate.
An example of lambda expression taking two parameters:
delegate int LambdaTest(int a,int b);
static void Main(string[] args)
{
LambdaTest sqr = (a,b) => a * b;
Console.WriteLine(sqr(3,9)); // 27
Console.ReadKey();
}
Lambda expressions are often used with Func and Action delegates:
static void Main(string[] args)
{
Func<int,int,int> sqr = (a,b) => a * b;
Console.WriteLine(sqr(3,9)); // 27
Console.ReadKey();
}
The first two arguments of the Func delegate are the types of arguments given in the expression, and the third type means the type of returned result and our returned result in the expression is of course int because the type int times the type int gives int.
Lambda expressions without arguments look like this:
static void Main(string[] args)
{
Func<int> sqr = () => 123;
Console.WriteLine(sqr()); //123
Console.ReadKey();
}
Anonymous methods
I do not know if you remember, but once we used the anonymous method in the lesson about events, the anonymous method is the method with the delegate word and no name and as you can also guess it uses delegates, let’s do one example with this method.
delegate int LambdaTest(int a);
static void Main(string[] args)
{
LambdaTest sqr = delegate(int b)
{
return b * 2;
};
Console.WriteLine(sqr(34)); // 68
Console.ReadKey();
}
The same with the use of lambda expressions will look like this:
delegate int LambdaTest(int a);
static void Main(string[] args)
{
LambdaTest sqr = b => b * 2;;
Console.WriteLine(sqr(34)); // 68
Console.ReadKey();
}
But you can also save it like this:
delegate int LambdaTest(int a);
static void Main(string[] args)
{
LambdaTest sqr = (int b) => { return b * 2; };
Console.WriteLine(sqr(34)); // 68
Console.ReadKey();
}
Curiosity
Certainly you used to be tempted at once to name a variable like her type, if you add a monkey character @ , you can do it, below is an example:
static void Main(string[] args)
{
string @string = "Now the variable name thanks to the ***monkey*** character can be the same as the type name";
Console.WriteLine(@string);
Console.ReadKey();
}
This content also you can find on my blog http://devman.pl/csharplan/c-language-lambda-expressions-anonymous-methods/
If you recognise it as useful, share it with others so that others can also use it.
Leave upvote and follow and wait for next articles :) .