#1,173 – Lambda Expression Can Be Just an Expression
September 2, 2014 Leave a comment
You’ll often see lambda expressions written as either a single statement (no return value) or a block of statements (optional return value).
static void SomeMethod(int i, string s) { // do something with int and string } static void Main(string[] args) { // Single statement Action<int, string> thing1 = (i, s) => SomeMethod(i, s); // Block of statements, no return value Action<int, string> thing2 = (i, s) => { for (int i2 = i; i2 <= i + 10; i2++) SomeMethod(i2, s); }; // Block of statements with return value Func<int,int> thing3 = (i) => { SomeMethod(i, "x"); return i + 1; }; }
A lambda expression can also be a single statement representing an expression whose type is assignment compatible with the return value of the delegate type being assigned to.
// Expression Func<int, int> doubleMe = (i) => 2 * i; Console.WriteLine(doubleMe(42));