Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is the type of lambda expression with a body?

Tags:

c#

.net

lambda

Windows forms extension method Invoke() doesn't accept a lambda expression, without us having to first typecast it to a delegate type like Action. This makes me wonder, if lambda expression (with a body) is not explicitly a delegate nor an expression, what is its type?

like image 572
Amit Dash Avatar asked Aug 07 '14 10:08

Amit Dash


2 Answers

This makes me wonder, if lambda expression (with a body) is not explicitly a delegate nor an expression, what is its type?

It doesn't have a type in the normal sense of the word (i.e. a CLR type), just like null doesn't have a type. (Older versions of the C# specification had the concept of a "null type", but that was removed.)

Instead, it's an expression which is convertible to any compatible concrete delegate or expression tree type.

See section 7.1 of the C# 5 specification ("Expression Classification") for details - the relevant bullet points (out of the list of kinds of expression) are:

  • A null literal. An expression with this classification can be implicitly converted to a reference type or nullable type.
  • An anonymous function. An expression with this classification can be implicitly converted to a compatible delegate type or expression tree type.
like image 168
Jon Skeet Avatar answered Nov 15 '22 07:11

Jon Skeet


Delegate is an abstract base class for all the delegates(MulticastDelegate comes in between). Lambda can't be converted to Delegate type as it can't be instantiated, and it doesn't have any signature.

So, You need to be more specific in saying what delegate type you're interested.

what is its type?

It has no type, it can be converted to any delegate type or Expression<TDelegate> type if the signature is compatible.

like image 32
Sriram Sakthivel Avatar answered Nov 15 '22 08:11

Sriram Sakthivel