C# Expression Bodied Members

We first saw expression bodied members introduced in C# 6. This introduced the ability to take a single expression method and read-only property and reduce it to a more concise form.

Functions

For example a single line function can be reduced from this:

public void WriteName(string name)
{
   Console.WriteLine(name);
}

To the following code below:

public void WriteName(string name) => Console.WriteLine(name);

Read-only Properties

A read-only property can be reduced from the following:

public string Firstname { get; set; }

public string Surname { get; set; }

public string FullName
{
  get { return Firstname + " " + Surname; }
} 

This read-only property can now be condensed to the following code below:

public string Firstname { get; set; }

public string Surname { get; set; }

public string FullName => Firstname + " " + Surname;

Now moving forward to C# 7, we now have support for: Property, Constructor, Finalizer and Indexer.

Properties

So for a property previously defined like this:

private string _name;

public string Name
{
  get { return _name; }
  set { _name = AlterName(value); }
}

private string AlterName(string name)
{
  return name.ToUpper();
}

This can now be re-written like so:

private string _name;

public string Name 
{
  get => _name;
  set => AlterName(value);
}

private string AlterName(string name)
{
  return name.ToUpper();
}

Constructors

A constructor written before C# 7 would look like this:

private string _name;
public Dog(string name)
{
   _name = name;    
}

With the expression bodied member syntax, the constructor definition becomes:

public class Pets
{
  private string[] _myPets = { "Cat", "Dog", "Rabbit", "Hamster" };

  public string this[int position]
  {
     get
     {
       return _myPets[position];
     }
     set
     {
       _myPets[position] = value;
     }
  }
}

The indexer becomes this in the C# 7 syntax:

public class Pets
{
  private string[] _myPets = { "Cat", "Dog", "Rabbit", "Hamster" };

  public string this[int position]
  {
     get => _myPets[position];
     set => _myPets[position] = value;
  }
}

Finalizers

A finalizer which can be written like this:

private string _name;

~Dog() => Console.WriteLine($"Destructor is executing for {_name}");

So what happens to the intermediate language?

If you inspect the intermediate language for the two different syntaxes, the generated intermediate language looks the same.

Conclusion

The benefits of using Expression Body Members over the older syntax are:

  • More compact code
  • More readable code
  • Syntactic sugar

For me, I prefer the expression bodied member syntax, for the reasons listed above. But you still might prefer the older syntax and find that more readable. So what do you think of the expression bodied member syntax?