Share via
Back

Implicitly typed lambda expressions

Written at 2016-03-04,
5 paragraphs,
9 sentences,
189 words.

Learn why you can't use an implicitly-typed variable declaration to declare a lambda expression.


Implicitly typed lambda expressions

You can't use an implicitly typed variable declaration to declare a lambda expression. It creates a circular logic problem for the compiler. The var declaration tells the compiler to figure out the type of the variable from the type of expression on the right hand side of the assignment operator. A lambda expression does not have a compile time type, but is convertible to any matching delegate or expression type. When you assign a lambda expression to a variable of a delegate or expression type, you tell the compiler to try and convert the lambda expression into an expression or delegate that matches the signature of the 'assigned to' variable. The compiler must try to make the thing on the right hand side of the assignment match the type on the left hand side of the assignment.

Both sides of the assignment can't be telling the compiler to look at the object on the other side of the assignment operator and see if my type matches.

You can get even more details on why the C# language specifies that behavior by reading this article (PDF Download)