Here we will discuss the Expression bodied members in C#.
Expression bodied members in C#
The expression bodied member in c# allows us to provide the implementation of member in a better readable format. We can use expression bodied members in C# whenever the logic for any supported members such as a method or property consists of a single expression.
Syntax: member => expression
The expression bodied member was introduced in C# 6 only methods and properties members, it enhanced in c# 7 the following members.
- Methods
- Properties
- Constructor
- Destructor
- Getters
- Setters
- Indexers
Method Expression bodied
An expression bodied method consists of a single expression that returns a value the type matches the method’s return type,
For example, types that override the ToString method typically include a single expression that returns the string representation of the object.
We will create a console application by following steps
Select Create a new project.
Search for console application and select click on next.
Configure your application like project name and location.
Select the target framework. in my scenario, I chose .NET 5.0 and click on create
The below example defines a student class that overrides the ToString method with an expression body definition.
It also defines a GetFullName method that returns the full name of the student and again It also defines a DisplayName method that displays the name to the console.
Note that the return keyword is not used in the ToString expression body definition.
class Program
{
static void Main(string[] args)
{
Student objstu = new Student("suryan", "suri", "A");
objstu.DisplayName();
Console.WriteLine(objstu);
Console.ReadKey();
}
}
public class Student
{
private string FirstName;
private string MiddleName;
private string LastName;
public Student(string firstName, string middleName, string lastName)
{
FirstName = firstName;
MiddleName = middleName;
LastName = lastName;
}
public string GetFullName() => $"{FirstName} {MiddleName} {LastName}";
public override string ToString() => $"{FirstName} {MiddleName} {LastName}";
public void DisplayName() => Console.WriteLine(GetFullName());
}
Generally, expression bodied methods are more used than other members.
Methods can even exhibit asynchronous behavior, if they return void, Task or Task<T>.