C# 7.0 improves the expression body feature

C# 6.0 already improved the expression body feature. With this improvement, a read-only property like this:


public string ExampleText
{
	get { return "this is my text"; }
}

can be rewritten in a shorter way:


public string ExampleText => "this is my text";

As you can see, with C# 6 the property is more compact and clearer. There are no more brackets, and no more return keyword; even the get accessor disappeared.

Personally, I use this C# 6 syntactic sugar very often, so I was happy to see that this feature was extended to constructors, destructors and setters.

Expression-Bodied Constructors

If you have a constructor that doesn't need a complex implementation, you can now reduce it to a single line.

C# 6

private bool Initialized = false;

public MyClass()
{
	Initialized = true;
}
C# 7

private bool Initialized = false;

public MyClass() => Initialized = true;

Expression-Bodied Destructors

The same is true for destructors:

C# 6

public ~MyClass()
{
	Console.WriteLine($"{nameof(MyClass)}'s destructor called");
}
C# 7

public ~MyClass() => Console.WriteLine($"{nameof(MyClass)}'s destructor called");

Expression-Bodied Property Accessors

This feature was available in C# 6 but only for read-only properties; with C# 7, you can now write your setters in the same compact way as the getters.

The next example is a simple case to show what the syntax is. In real life you could be simpler than this by using an auto property, which reduces the code even more, but let's see how you can implement a very simple property with the C# 7 improvement:

C# 6

private string _exampleText;
public string ExampleText
{
	get { return _exampleText; }
	set { _exampleText = value; }
}
C# 7

private string _exampleText;
public string ExampleText
{
	get => _exampleText;
	set => _exampleText = value;
}

Summary

It's clear that Microsoft wants to continue with productivity enhancements for the next version of C#, which is such a good thing. The fewer words you have in your code, the less time you spend writing, reading and understanding it.

To keep informed about the evolution of C#, you can read the design notes discussed on GitHub, they are really interesting.

February 1, 2017
  • C#
  • Csharp
  • C# 7.0