Expression-Bodied Members
Expression-bodied members is a feature introduced in C# 6 that allows you to use lambda-like syntax to simplify writing of methods, properties, operator overloads, and indexers of a class. Instead of writing the body of a member, you use a notation similar to a lambda expression. As an example, consider this simple method that returns the sum of its two parameters.
public int GetSum(int x, int y)
{
return x + y;
}
By using expression-bodied member feature, you can reduce this definition into a single line like this:
public int GetSum(int x, int y) => x + y;
We simply write the same signature, but the body starts with the => operator then followed by the expression being returned, similar to a lambda expression. We also don’t need to write the return keyword.
We can also do this for properties as well. Consider the following read-only property that returns the full name of a person.
public string FullName
{
get
{
return FirstName + " " + LastName;
}
}
We can now write it as this:
public string FullName => FirstName + " " + LastName;
For methods that return void and has only a single statement as a body, we can also rewrite them to use the expression bodied-member feature.
public void PrintMessage(string message) => Console.WriteLine(message);
Expression-bodied members can also be applied to indexers and operator overloads.
// Indexer
public int this[int index] => InternalCollection[index];
// Operator Overload
public static Point operator +(Point p1, Point p2) => new Point(p1.X + p2.X, p1.Y + p2.Y);
// Conversion Overload
public static implicit operator string(Point point) => $"({point.X}, {point.Y})";
You may be asking whether we can convert multiple-statement bodies into expression-bodied members, just like lambda expressions where we enclose the statements into curly braces. The answer is no. Expression-bodied members are only useable if a member only has a single line of code inside it. If it has multiple lines, then it is worthless to convert it into an expression-bodied member as you will use curly braces either way. Again, the goal of expression-bodied members is to simplify members with single-statement in their body.