X

Expression Bodied Accessors in C#

Csharp-MS-Dotnet

In C# 7 there are Expression Bodied Accessors which allows you to write getter and setters somewhat more functional way, somewhat lambda’ish. Let me show you an example. You may remember the old way of writing getter and setters like below.

Pre Expression Bodied Accessors Getter and Setter

public class Automobile 
{
  private string _brand;
  public string Brand 
  {
    get { return _brand; }
    set { _brand = value; }
  }
}

Expression Bodied Accessors in C# 7

When using C# 7 you can use Expression Bodied Accessors like below which makes the code wayyyyy cleaner in my opinion. As you can see below, I have also added the null exception into the setter.

public class Automobile 
{
  private string _brand;
  public string Brand 
  {
    get => _brand;
    set => _brand = value ?? throw new ArgumentNullException("value")
  }
}

Summary

I hope I have explained how Expression Bodied Accessors can make your code way cleaner and easier to understand, not to mention that you can include exception into the setter since Exceptions are also Expression now. If you wish to learn more you can also visit Microsoft Learn Site on Express Bodied Accessors. Btw you can also use the Expression Accessors for Constructors and Destructors.

Categories: .NET C#
Tags: csharpdotnet
Taswar Bhatti:
Related Post