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
- get { return string.Format("{0} {1} {2} {3}", 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 UserDetails
-
- {
-
- get { return string.Format("{0} {1} {2} {3}", UserId, UserName, EmailId, ContactNumber); }
-
- }
-
- }
In C# 6
- public string UserDetails => $"{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 UserDetails => $"{UserId} {UserName} {EmailId} {ContactNumber}";
-
- }
Or
- class User
-
- {
-
- public int UserId { get; } = 1001;
-
- public string UserName { get; } = "BNarayan";
-
- public string EmailId { get; } = "[email protected]";
-
- public string ContactNumber { get; } = "99xxxxxxxx";
-
- public string UserDetails => $"{UserId} {UserName} {EmailId} {ContactNumber}";
-
- }
Example 2:
In C# 5
- public class Rectangle
-
- {
-
- public double Width { get; set; }
-
- public double Lenght { get; set;}
-
- public double Area { get { return Width * Lenght; } }
-
- }
In C# 6
- public class Rectangle
-
- {
-
- public double Width { get; set; } = 10.0;
-
- public double Lenght { get; set; } = 10.0;
-
- public double Area => Width * Lenght;
-
- }