#1,217 – C# 6.0 – Using Expression-Bodied Methods
November 3, 2014 5 Comments
In C# 5.0, you could use a lambda expression wherever a delegate instance was expected. For example:
Func doubleMyNumber = (i) => 2 * i;
In C# 6.0, you use something similar for the body of a function member, known as an “expression-body definition” to define the method. This simplifies the syntax for simple methods. For example:
public class Dog { public Dog(string name, int age) { Name = name; Age = age; } public string Name { get; protected set; } public int Age { get; set; } public void AgeIncrement() => Age++; public int AgeInDogYears() => Age * 7; }
Pingback: Dew Drop – November 3, 2014 (#1890) | Morning Dew
Technically, it isn’t a lambda expression.
While this is using lambda syntax, it isn’t a lambda expression and the compiler isn’t converting anything to delegates. BTW, great work on this C# and the WPF series – very useful.
Does the syntax allow you to enclose the lambda expression within parentheses, for better readability?
Example:
Func doubleMyNumber = ((i) => 2 * i); // Parens added
Yes, you can always put parens around the lambda (wherever it’s used).