Expression body definitions let you provide a member's implementation in a very concise, readable form. You can use an expression body definition whenever the logic for any supported member, such as a method or property, consists of a single expression.
General syntax:
member => expression;
Constructors & Finalizers
An expression body definition for a constructor typically consists of a single assignment expression or a method call that handles the constructor's arguments or initializes instance state. The finalizer typically contains cleanup statements, such as statements that release unmanaged resources.
class Student
{
private string _fullName;
//Constructors
public Student(string fullName) => _fullName = fullName;
//Finalizers
~Student() => _fullName = null;
}
Property
public class Teacher
{
private string _firstName;
private string _lastName;
//get & set
public string FirstName
{
get => _firstName;
set => _firstName = value;
}
//get & set
public string LastName
{
get => _lastName;
set => _lastName = value;
}
//get
public string FullName => $"{FirstName} {LastName}";
}
Of course, in such scenario you would prefer to use an auto property which even simplify the code more.
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName => $"{FirstName} {LastName}";
However, this could be more useful when your properties required explicit get or set. For example when you implement an INotifyPropertyChanged.
Indexers
Like properties, an indexer's get and set accessors consist of expression body definitions if the get accessor consists of a single statement that returns a value or the set accessor performs a simple assignment.
public class Language
{
private string[] languages = { "C#", "VB.NET", "F#", "Java" };
public string this[int i]
{
get => languages[i];
set => languages[i] = value;
}
}