Expression – Bodied Members in C# 7.0

Expression – Bodied Members in C# 7.0

Expression-bodied methods was introduced with C# 6.0, that simplify the syntactic expression for methods in C#. We have seen this for Methods and Properties in the previous version of C#. C# 7.0 extend this features for several new members including  constructor, destructor, property assessors etc.

Consider you have following method in your application

public static string GetTime()
{
return "Current Time - " + DateTime.Now.ToString("hh:mm:ss");
}

In C# 6.0, you could rewrite it as follow with the help of Expression-bodied methods.

public static string GetTime() =>  "Current Time - " + DateTime.Now.ToString("hh:mm:ss");

With C# 7.0, we extend this for other members including constructor and destructor.

class Student
{
private string studentName;

// Expression – Bodied Constructor
public Student(string name) => studentName = name;

// Expression – Bodied Destructor
~Student() => studentName = null;
}

Similarly, we can even do it for Properties as well,

public string Name
{
get => studentName;
set => studentName = value;
}

Of course in such scenario, you would prefer to use an auto property, which even simplify the code more. However, this could be more useful when your properties required explicit getter / setter – for an example, implement INotifyPropertyChanged.

It is simple, and if you are working with lambda expressions, it would even look more straight forward. This provide a very clean syntax and reduce line of codes. You also need to keep in mind, Expression bodied members doesn’t support block of code,  it is only for when you have a single statement to execute with in the members.

Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.