Delegate is clear to understand
delegate int del(int i);
but why can we use
del myDelegate = x => x * x;
Questions here:
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With