Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the actual type of lambda in C#?

Tags:

c#

lambda

func

People also ask

What is the type of a lambda?

A type lambda lets one express a higher-kinded type directly, without a type definition. For instance, the type above defines a binary type constructor, which maps arguments X and Y to Map[Y, X] . Type parameters of type lambdas can have bounds, but they cannot carry + or - variance annotations.

Is there lambda in C?

the C standard does not define lambdas at all but the implementations can add extensions. Gcc also added an extension in order for the programming languages that support lambdas with static scope to be able to convert them easily toward C and compile closures directly.

What is the return type of lambda?

The return type for a lambda is specified using a C++ feature named 'trailing return type'. This specification is optional. Without the trailing return type, the return type of the underlying function is effectively 'auto', and it is deduced from the type of the expressions in the body's return statements.

What is the type of a lambda expression C#?

Lambda expressions in C# are used like anonymous functions, with the difference that in Lambda expressions you don't need to specify the type of the value that you input thus making it more flexible to use. The '=>' is the lambda operator which is used in all lambda expressions.


A lambda expression doesn't have a type. It cannot, because any type in the .NET world that it could have, would also hard-code the type of the lambda's parameters and result. Now consider:

x => x + 1

What type could x have? What type will the result be? There isn't any single answer, and the lambda expression can indeed be converted to Func<int, int>, Func<double, double>, and many other delegate types with different parameters. Giving a lambda expression a type would disallow such expressions. C# did want to allow such expressions, so was designed not to give such expressions any type.


This is because () => 5 can be compatible with various delegate types (e.g. you may have a custom delegate that takes nothing and returns int). And in order to create a delegate, compiler has to know the exact type. It can't just pick a random type that suits your needs. So that's why unless you cast it to an actual delegate type, you can't Invoke it.

In cases like where a method expects a delegate, that conversion is implicitly done by the compiler:

void Foo(Func<int> func) {  }

Foo(() => 5); 

And it is also important to know that delegates are actually classes behind the scenes. And each time you create a delegate instance, compiler creates an instance of that class. So either way you have to specify a type so the compiler will know which type to use.