Expression Bodies In C# 7.0

A new feature introduced with the release of C# 7.0 is Expression Bodies. This feature makes your code more readable and can reduce the number of lines of code drastically. 

There are 3 types of Expression Bodies introduced in C# 7.0 -

Accessor

Generally, while declaring properties, we use the Get as well as Set accessor and these are used to return and set the value a private member. For the Get accessor, we just return a private member. For this, we generally have a code block with {} braces and in between, we write a written statement. For this, it will take 3 to 4 lines of code. Do we really need this? Of course, no! In C# 7.0, now we can reduce such implementation in one line. Similarly, we can do that for Set Accessor. 

Constructor 

The same as above, here, we can have small constructors (injecting one or two variables to class properties) in 1 or 2 lines instead of 5 to 6 lines of code. 

Finalizer 

I hope I have no need to explain this too. It is understood that we can cut short even the Finalizer, or we can say destructors. 

Now, we can go into action. Below is the code snippet of what we used to do before C# 6.0. 

  1. public class ExpressionBodiesOld {  
  2.     private string _myName;  
  3.     public string MyName {  
  4.         get {  
  5.             return _myName;  
  6.         }  
  7.         set {  
  8.             if (value != null) _myName = value;  
  9.             else throw new ApplicationException("Cannot be null");  
  10.         }  
  11.     }  
  12.     public ExpressionBodiesOld(string name) {  
  13.         MyName = name;  
  14.     }~ExpressionBodiesOld() {  
  15.         Console.WriteLine("Released");  
  16.     }  
  17. }  

As observed, it took almost 28 lines. Now, mentioned below is the simplified code of the above by applying Expression Bodies feature which took 18 lines of code. So, we saved 10 lines of code with more readability. 

  1. public class ExpressionBodies {  
  2.     private string _myName;  
  3.     public string MyName {  
  4.         // Expression bodied get accessor   
  5.         get => _myName;  
  6.         // Expression bodied set accessor along with exception expression   
  7.         set => _myName = value ? ?  
  8.             throw new ApplicationException("Cannot be null");  
  9.     }  
  10.     // Expression bodied constructor   
  11.     public ExpressionBodies(string name) => MyName = name;  
  12.     // Expression bodied finalizer   
  13.     ~ExpressionBodies() => Console.WriteLine("Released");  
  14. }  

I hope this explanation gives you the concept. 

You can see the complete code here on GitHub.

Happy Coding :) 

Next Recommended Reading C# 7.0 New Feature - Tuples In C# 7