Expression-Bodied Properties in C# 6

In C# 6 Microsoft has introduced Expression-bodied Method and properties. Here I am go to explain only about Expression-bodied Properties if you are interested to know about Expression-bodied method then check here .It’s inspired by lambda expression.

In C# 5

  1. get { return string.Format("{0} {1} {2} {3}", UserId, UserName, EmailId, ContactNumber); }   
Complete code
  1. class User  
  2.   
  3. {  
  4.   
  5. public int UserId { getset; }  
  6.   
  7. public string UserName { getset; }  
  8.   
  9. public string EmailId { getset; }  
  10.   
  11. public string ContactNumber { getset; }  
  12.   
  13. public string UserDetails  
  14.   
  15. {  
  16.   
  17. get { return string.Format("{0} {1} {2} {3}", UserId, UserName, EmailId, ContactNumber); }  
  18.   
  19. }  
  20.   

In C# 6

  1. public string UserDetails => $"{UserId} {UserName} {EmailId} {ContactNumber}";   
Complete Code
  1. class User  
  2.   
  3. {  
  4.   
  5. public int UserId { getset;}  
  6.   
  7. public string UserName { getset; }  
  8.   
  9. public string EmailId { getset; }  
  10.   
  11. public string ContactNumber { getset; }  
  12.   
  13. public string UserDetails => $"{UserId} {UserName} {EmailId} {ContactNumber}";  
  14.   

Or

  1. class User  
  2.   
  3. {  
  4.   
  5. public int UserId { get; } = 1001;  
  6.   
  7. public string UserName { get; } = "BNarayan";  
  8.   
  9. public string EmailId { get; } = "[email protected]";  
  10.   
  11. public string ContactNumber { get; } = "99xxxxxxxx";  
  12.   
  13. public string UserDetails => $"{UserId} {UserName} {EmailId} {ContactNumber}";  
  14.   

Example 2:

In C# 5

  1. public class Rectangle  
  2.   
  3. {  
  4.   
  5. public double Width { getset; }  
  6.   
  7. public double Lenght { getset;}  
  8.   
  9. public double Area { get { return Width * Lenght; } }  
  10.   

In C# 6

  1. public class Rectangle  
  2.   
  3. {  
  4.   
  5. public double Width { getset; } = 10.0;  
  6.   
  7. public double Lenght { getset; } = 10.0;  
  8.   
  9. public double Area => Width * Lenght;  
  10.   

Next Recommended Reading Understanding Lambda Expressions in C#