Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can lambdas convert function calls into Actions?

Tags:

c#

.net

c#-4.0

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?

like image 889
Adam Lee Avatar asked Oct 13 '12 02:10

Adam Lee


People also ask

What is the point of lambdas?

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.

How do lambda functions work C#?

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.

Why do we use lambda expression in C#?

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.

How do you read lambda expressions?

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.


1 Answers

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.

like image 153
Sergey Kalinichenko Avatar answered Oct 04 '22 00:10

Sergey Kalinichenko