Creating expression-bodied methods
The following example shows how you might have created a method before C# 6.0:public int RectArea(Rectangle rect)
{
return rect.Height * rect.Width;
}
When working with an expression-bodied member, you can reduce the number of lines of code to just one line, like this:
public int RectArea(Rectangle rect) => rect.Height * rect.Width;
Even though both versions perform precisely the same task, the second version is much shorter and easier to write. The trade-off is that the second version is also terse and can be harder to understand.
Defining expression-bodied properties
Expression-bodied properties work similarly to methods: You declare the property using a single line of code, like this:public int RectArea => _rect.Height * _rect.Width;
The example assumes that you have a private member named _rect
defined and that you want to get the value that matches the rectangle’s area.
Defining expression-bodied constructors and destructors
In C# 7.0, you can use this same technique when working with a constructor. In earlier versions of C#, you might create a constructor like this one:public EmpData()
{
_name = "Harvey";
}
In this case, the EmpData
class constructor sets a private variable, _name
, equal to "Harvey"
. The C# 7.0 version uses just one line but accomplishes the same task:
public EmpData() => _name = "Harvey";
Destructors work much the same as constructors. Instead of using multiple lines, you use just one line to define them.
Defining expression-bodied property accessors
Property accessors can also benefit from the use of expression-bodied members. Here is a typical C# 6.0 property accessor with bothget
and set
methods:private int _myVar;
public MyVar
{
get
{
return _myVar;
}
set
{
SetProperty(ref _myVar, value);
}
}
When working in C# 7.0, you can shorten the code using an expression-bodied member, like this:
private int _myVar;
public MyVar
{
get => _myVar;
set => SetProperty(ref _myVar, value);
}
Defining expression-bodied event accessors
As with property accessors, you can create an event accessor form using the expression-bodied member. Here’s what you might have used for C# 6.0:private EventHandler _myEvent;
public event EventHandler MyEvent
{
add
{
_myEvent += value;
}
remove
{
_myEvent -= value;
}
}
The expression-bodied member form of the same event accessor in C# 7.0 looks like this:
private EventHandler _myEvent;
public event EventHandler MyEvent
{
add => _myEvent += value;
remove => _myEvent -= value;
}