Friday, January 13, 2017

Assigning lambda expression to a variable

In the spirit of writing terse code, I was pleasantly surprised that you can assign a lambda expression to a local variable. A quick sample:
void Main()
 Func<string, string> sayHello = ((input) => { return input + "!!"; });
 System.Diagnostics.Debug.WriteLine(sayHello("hello world"));

hello world!!

in Func<string, string>, the first string specifies the input parameter's data type, while the last string is for the return type. If you have more than one input parameter, you'd have multiple parameters specified like this <string, string, stringstring> and the last one is always for the return type of the function.

No comments: