Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confusion about the lambda expression and delegate?

Tags:

c#

.net

c#-4.0

Delegate is clear to understand

delegate int del(int i);

but why can we use

del myDelegate = x => x * x; 

Questions here:

  1. How can I assure x is int type in the lambda expresison?
  2. How can I know lambda expression return a int?
like image 449
Adam Lee Avatar asked Jul 14 '26 16:07

Adam Lee


1 Answers

C# compiler is smart enough to implicitly figure out the type of x on the left side of => from the context. Since it knows that you are assigning the lambda to a variable of type del, the compiler knows that x is an int.

As far as the return type goes, the compiler knows that x is an int, therefore the type of the x * x expression must also be int. That's how the compiler knows the return type of the lambda.

Note that the same code would not have compiled without the exact type of myDelegate specified:

// This does not compile!
var myDelegate = x => x*x;
like image 145
Sergey Kalinichenko Avatar answered Jul 16 '26 06:07

Sergey Kalinichenko