Consider this snippet 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 return(false)" statement - the compiler warns that not all code paths return a value. But in the following code, which uses a lambda...
Func<int, bool> TestGreaterThanOne = a => a > 1;
I do not have to have an "else" statement - there are no compiler warnings and the logic works as expected.
What mechanism is at play here to make me not have an "else" statement in my lambda?
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.
In this article In C++11 and later, a lambda expression—often called a lambda—is a convenient way of defining an anonymous function object (a closure) right at the location where it's invoked or passed as an argument to a function.
They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection .
The reason why lambda functions become so useful is the fact that it is usually more convenient to use simple and concise lambda notation rather than defining a new function in a traditional way, especially if the function is designed to do only one single operation rather than serve as a repeatable component.
Because in your lambda shorthand, there is no if statement either. Your lambda shorthand is equivalent to
Func<int, bool> TestGreaterThanOne = delegate(int a) {
return (a > 1);
};
Therefore all code paths return a value.
To add slightly to the other responses, in your lambda statement, a > 1
evaluates to a boolean, which is then returned.
Generally, writing return true;
and return false;
statements is considered redundant. It's simpler to just return whatever the expression evaluates to.
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