In this code fragment:
List<String> names = new List<String>();
names.Add("Bruce");
names.Add("Tom");
names.Add("Tim");
names.Add("Richard");
names.ForEach(x => Print(x));
private static string Print(string s)
{
Console.WriteLine(s);
return s;
}
Print
is not an Action
for sure since it is returning string
; however x=> Print(x)
is, why?
Lambda functions are intended as a shorthand for defining functions that can come in handy to write concise code without wasting multiple lines defining a function. They are also known as anonymous functions, since they do not have a name unless assigned one.
Lambda expressions in C# are used like anonymous functions, with the difference that in Lambda expressions you don't need to specify the type of the value that you input thus making it more flexible to use. The '=>' is the lambda operator which is used in all lambda expressions.
Lambda expressions are like anonymous methods but with much more flexibility. When using a lambda expression, you don't need to specify the type of the input. Hence, a lambda expression provides a shorter and cleaner way of representing anonymous methods.
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 hold the expression or statement block. The lambda expression x => x * 2 is read "x goes to 2 times x." This reduced the no.
The type of the lambda expression x => Print(x)
is determined based on its context. Since the compiler knows that the lambda is assigned to Action<string>
, the compiler disregards the return type of the Print(s)
method as if it were a statement expression.
This is a valid conversion:
Action<string> myAction = y => Print(y);
In other words, both
Print("something");
and
int x = Print("something");
are correct usages of the Print
method; they can be used in lambdas in the same way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With