Lambda & anonymous methods C# with Example



Lambda & anonymous methods C# with Example

An anonymous method can be assigned wherever a delegate is expected: 
Func square = delegate (int x) { return x * x; } 
Lambda expressions can be used to express the same thing: 
Func square = x => x * x; 
In either case, we can now invoke the method stored inside square like this: 
var sq = square.Invoke(2); 
Or as a shorthand: 
var sq = square(2); 
Notice that for the assignment to be type-safe, the parameter types and return type of the anonymous method 
must match those of the delegate type: 
Func sum = delegate (int x, int y) { return x + y; } // error 
Func sum = (x, y) => x + y; // error 

0 Comment's

Comment Form