Expression - Bodied Methods in C# 6

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,

  1. public string GetUserDetails() => $"{UserId} + {UserName} + {EmailId} + {ContactNumber}"

Complete Code

  1. class User    
  2. {    
  3.    public int UserId { getset; }  
  4.    public string UserName { getset; }  
  5.    public string EmailId { getset; }  
  6.    public string ContactNumber { getset; }  
  7.    public string GetUserDetails() => $"{UserId} + {UserName} + {EmailId} + {ContactNumber}";  
  8. }  

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,

  1. public override string ToString()=> $"{UserId} + {UserName} + {EmailId} + {ContactNumber}"

Complete code

  1. class User    
  2. {  
  3.    public int UserId { getset; }  
  4.    public string UserName { getset; }  
  5.    public string EmailId { getset; }  
  6.    public string ContactNumber { getset; }  
  7.    public string GetUserDetails() => $"{UserId} + {UserName} + {EmailId} + {ContactNumber}";  
  8.    public override string ToString()=> $"{UserId} + {UserName} + {EmailId} + {ContactNumber}";  
  9. }  

Example 3: Creating a Virtual method using Expression-bodied Method and override it.

  1. public virtual string GetUserDetails() => $"{UserId} + {UserName} + {EmailId} + {ContactNumber}";  
  2. public override string GetUserDetails() => $"{UserId} + {UserName} + {EmailId} + {ContactNumber} + {Rank}";  

Complete code

  1. class User  
  2. {  
  3.   public int UserId { getset; }  
  4.   public string UserName { getset; }  
  5.   public string EmailId { getset; }  
  6.   public string ContactNumber { getset; }  
  7.   public virtual string GetUserDetails() => $"{UserId} + {UserName} + {EmailId} + {ContactNumber}";  
  8.   public override string ToString()=> $"{UserId} + {UserName} + {EmailId} + {ContactNumber}";  
  9. }  
  10.   class SilverUser : User  
  11.   {  
  12.      public int Rank { getset; }  
  13.      public override string GetUserDetails() => $"{UserId} + {UserName} + {EmailId} + {ContactNumber} + {Rank}";  
  14.   }  
Ebook Download
View all
Learn
View all