Func<int,bool> without return keyword in Linq?
c#, lambda, linq
Solution
This type of lambda expression is called an expression lambda:
n => n > 10
In expression lambdas, what follows `=>` must be an expression and the return type is inferred by the compiler. One of the consequences is that you cannot use expression lambda syntax to create a lambda with a `void` return type.
There is another syntax for lambdas, called statement lambda:
n => { return n > 10; }
Here the `=>` is followed by a block containing one or more statements; if you want to return a value you must do so explicitly, and it's also possible to have a `void` return type (don't return anything).
Note that support for statement lambdas was only added in .NET 4.0, and in general is worse throughout the framework than that for expression lambdas, e.g. many (all?) LINQ query providers will refuse to work with statement lambdas even if they can be trivially written as the equivalent expression lambda.
Problem
While using Linq I stumbled upon the following expression: ``` bool biggerThan10Exists = numbers.Any(n => n > 10); ``` The definition for Any is as follows: ``` public static bool Any<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate ) ``` The definition for Func is as follows: ``` public delegate TResult Func<in T, out TResult>( T arg ) ``` So if Any requires a Func which requires delegates to be passed that returns an int, how comes I can pass a lambda expression that in my opinion is a definition of a void delegate, i.e. ``` n => n > 10 ``` While I would expect ``` n => return n > 10 ``` I'm pretty sure I'm obviously missing something here, but what?