Expression Bodied Members in C#

Posted in software by Christopher R. Wirz on Tue Jan 13 2015



Expression bodied members are a feature of C# 6.0 and provide an inline expression for properties (get only properties) and methods. This syntax is more concise, but decreases readability for multi-line underlying logic involving extensive LINQ expressions. Branching statements (if/else, switch, try) and looping statements (for, foreach, while, and do) are also not allowed (however, LINQ statements are allowed).

Note: Visual Studio 2015 is required.

Consider the following example of a method.


public int TimesNineThousand(int someValue)
{
    return someValue * 9000;
}

This could be more beautifully written as an expression bodied member as follows:


public int TimesNineThousand(int someValue) => someValue * 9000;

This also works for extension methods.


public static int TimesNineThousand(this int someValue) => someValue * 9000;

Note: Static methods and properties are evaluated when called, not at initialization.

Note how in the above examples, the curly braces ({ }), are replaced with the lambda arrow (=>). This can be done for public, protected, internal, private, and protected internal methods. Expression bodied members can be virtual, override a base class method. Also, methods can be asynchronous (returning void, Task, or Task).

Note: It is bad practice to make an Expression bodied member abstract, which cannot declare a body.

Consider the following get-only property.


public int Index
{
	get 
	{
		return _index;
	}
}

This can be re-written as follows:


public int Index => _index;

As an additional point, the async modified can be used with an await expression - as long as the await preceeds a method that returns a Task type. The following is a commonly discussed example:


public async Task ReadFromWeb() => await RunReadFromWeb();

public Task RunReadFromWeb()
{
    return this.RunWebRequest();
}

Without the await, it won't actually be run on a background thread.

The final expression bodied member feature to discuss is operators.


public static SomeClass operator +(SomeClass left, SomeClass right)
{
	return new SomeClass(left.IntValue + right.IntValue);
}

This can be re-written as follows


public static SomeClass operator +(SomeClass left, SomeClass right)
	=> return new SomeClass(left.IntValue + right.IntValue);

Looking for a job?