MistyD
MistyD

Reputation: 17233

How do C# lambdas work without a “return”?

I have occasionally come across statements like this

school.Where(s => s.name == "foo") 

Now I understand this is a lambda and I think I am comfortable with lambdas. I just started C# so I do have this question. In the statement

s => s.name == "foo"

how is the evaluation return being done to determine true or false. I do not see a return statement ? All i see is a comparison operation in the lambda body and nothing being returned. Can anyone please explain this to me.

Upvotes: 1

Views: 599

Answers (4)

Michał Turczyn
Michał Turczyn

Reputation: 37430

Lambda can be defined in two ways:

  • with curly braces: then you will have to write body of a method, just like in a regular method, i.e. with returns, etc. Example

    var lambda = (string param) => { return param.Length; };
    
  • without curly braces: then the method has to contain one line, which also be the result of a method. Example:

    var lambda = (string param) => param.Length;
    

This is by design, to make one-line methods look nice and clean (especially in LINQ extensoin methods) :)

Upvotes: 1

Mortaza Ghahremani
Mortaza Ghahremani

Reputation: 392

The returned value is always boolean and you can get it like below:

s=> {retutn s.name=="foo";}

Upvotes: 0

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31193

In this form the return is implicit. The lambda returns whatever the expression returns. You could also write it like this:

s => { return s.name == "foo"; }

The reason why the return isn’t needed in the short form is because that’s how the language was designed. It makes things short and nice to use instead of forcing the developer to write unnecessary code.

Upvotes: 9

Batman
Batman

Reputation: 702

The return statement is implied. If you were to add brackets around s.name == "foo" then you'd have to have a return. The compiler essentially creates a function to be called there for you. This is just syntax sugar. It's equivalent to creating a function yourself and passing that into the Where

Upvotes: 1

Related Questions