Expression bodied member extended

Expression bodied member extended

Expression bodied members were introduced in C# 6.0 where the syntactical expression of the method can be written in a simpler way. In C# 7.0, we can use this feature with a constructor, a destructor, an exception, and so on.

The following example shows how the constructor and destructor syntactic expressions can be simplified using expression bodied members:

public class PersonManager 

{

//Member Variable

Person _person;

//Constructor

PersonManager(Person person) => _person = person;

//Destructor

~PersonManager() => _person = null;

}

With properties, we can also simplify the syntactic expression, and the following is a basic example of how this can be written:

private String _name; 

public String Name

{

get => _name;

set => _name = value;

}

We can also use an expression bodied syntactic expression with exceptions and simplify the expression, which is shown as follows:

private String _name; 

public String Name

{

get => _name;

set => _name = value ?? throw new ArgumentNullException();

}

In the preceding example, if the value is null, a new ArgumentNullException will be thrown.