In C# 6 Microsoft introduces a new feature Expression-bodied Methods which is very similar to and inspired by anonymous lambda expression. But there are some differences between these two.
In case of Expression-bodied methods it must have return type, name and returned expression.
We can use access modifiers (private, public, protected, internal and protected internal) with expression-bodied method. We can declare it as virtual, static or it can also override its parent class method. It can be asynchronous if it is returning void.
Example 1: Expression-bodied method having access modifier as public and return type string,
- public string GetUserDetails() => $"{UserId} + {UserName} + {EmailId} + {ContactNumber}";
Complete Code
- class User
- {
- public int UserId { get; set; }
- public string UserName { get; set; }
- public string EmailId { get; set; }
- public string ContactNumber { get; set; }
- public string GetUserDetails() => $"{UserId} + {UserName} + {EmailId} + {ContactNumber}";
- }
In the above example GetUserDetails() method is having access modifier public and return type string.
Example 2: Override an existing method using Expression-bodied Method,
- public override string ToString()=> $"{UserId} + {UserName} + {EmailId} + {ContactNumber}";
Complete code
- class User
- {
- public int UserId { get; set; }
- public string UserName { get; set; }
- public string EmailId { get; set; }
- public string ContactNumber { get; set; }
- public string GetUserDetails() => $"{UserId} + {UserName} + {EmailId} + {ContactNumber}";
- public override string ToString()=> $"{UserId} + {UserName} + {EmailId} + {ContactNumber}";
- }
Example 3: Creating a Virtual method using Expression-bodied Method and override it.
- public virtual string GetUserDetails() => $"{UserId} + {UserName} + {EmailId} + {ContactNumber}";
- public override string GetUserDetails() => $"{UserId} + {UserName} + {EmailId} + {ContactNumber} + {Rank}";
Complete code
- class User
- {
- public int UserId { get; set; }
- public string UserName { get; set; }
- public string EmailId { get; set; }
- public string ContactNumber { get; set; }
- public virtual string GetUserDetails() => $"{UserId} + {UserName} + {EmailId} + {ContactNumber}";
- public override string ToString()=> $"{UserId} + {UserName} + {EmailId} + {ContactNumber}";
- }
- class SilverUser : User
- {
- public int Rank { get; set; }
- public override string GetUserDetails() => $"{UserId} + {UserName} + {EmailId} + {ContactNumber} + {Rank}";
- }