Why does lambdas in C # seem to handle return booleans differently?

Consider this piece of code:

Func<int, bool> TestGreaterThanOne = delegate(int a) { if (a > 1) return (true); else return(false); }; 

In the above code, I cannot delete the else else return (false) statement. The compiler warns that not all code paths return a value. But in the following code that uses lambda ...

 Func<int, bool> TestGreaterThanOne = a => a > 1; 

I don’t need to have an β€œelse” statement - there are no compiler warnings, and the logic works as expected.

What mechanism does play here so that I don't have an "else" expression in my lambda?

+6
source share
5 answers

Because in your lambda abbreviation there is also no if statement. Cutting your lambda is equivalent

 Func<int, bool> TestGreaterThanOne = delegate(int a) { return (a > 1); }; 

Therefore, all code paths return a value.

+21
source

To add a little to the other answers, in your statement lambda, a > 1 computes a boolean value, which is then returned.

Typically, entries return true; and return false; considered excessive. It’s easier to simply return what evaluates the expression.

+2
source

As an alternative to rewriting a delegate, you lambda abstraction is equivalent

 Func<int, bool> TestGreaterThanOne = a => { if (a > 1) return (true); else return(false); }; 

If you cannot delete the else branch. Because he will not return either. The current version works because a > 1 is a boolean (which is always present).

+1
source

I do not think they handle booleans differently in the case you mention. The code just does two different things. Since you define Func as Func<int, bool> , it requires a logical return value. The second part of the code always returns a boolean value. However, the first part of the code does not return a boolean unless you include else.

0
source

a>1 itself is boolean, and so your lambda is working. you can almost think of an if expression as a function that takes a boolean parameter, so you can do something like

 boolean b = true if(b) doSomething(); 

and it compiles and does doSomething

0
source

Source: https://habr.com/ru/post/920240/


All Articles