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.
Pingback: Dew Drop - July 18, 2017 (#2522) - Morning Dew
Add to mailing list
Pingback: The week in .NET – MIST, F# in NYC, and links | .NET Blog
Pingback: Directly throw Exception as an Expression – Throw expressions in C# 7.0
Pingback: Expression Bodied for Local Function in C# 7.0