C# 7.0 improves the expression body feature

C# 6.0 already improved the expession 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 th property is more compact, more clear. There is no more brackets, or return keyword anymore; even the get accessor disappeared.

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

Expression-Bodied Constructors

If you have a constructor who doesn't need complex implementation, you can now reduce him to only one 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 with C# 6 but only for read-only properties, but with C# 7, you can now write your setters in the same compact way than the getters.

The next example is a simple case to see what the syntax is, but in the real-life you could be more simple that this using an auto property who will reduces the code 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#, such a good thing. The less words you have in your code, the less time you spend to write, read and understand it.

To keep you inform about the evolution of C#, you can read the design notes discussed on GitHub, such interesting.

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