Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do lambdas in c# seem to handle boolean return values differently?

Tags:

c#

lambda

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?

like image 230
Michael Ray Lovett Avatar asked Jul 11 '12 15:07

Michael Ray Lovett


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.

What is lambdas in C?

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.

Why do we need lambda expressions?

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 .

Are lambdas useful?

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.


2 Answers

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.

like image 194
Raymond Chen Avatar answered Sep 18 '22 18:09

Raymond Chen


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.

like image 20
MgSam Avatar answered Sep 19 '22 18:09

MgSam