Expression Bodied Members In C#

In this article, I am going to share with you about Expression Bodied Members in C#
 
What is Expression Bodied Members?
  1. Expression Bodied member was introduced in C#6.0 and enhanced in C#7.0.
  2. Expression Bodied is a new technique or implementation to make code concise and readable.
  3. Expression Bodied makes the type member(Constructor, Destructor, Methods, Property, Indexer) defined in a single expression.
  4. Expression Bodied members can only be applied to the below list of type members:
    • Constructor introduced in C#7.0
    • Destructor introduced in C#7.0
    • Property get accessor introduced in C#6.0
    • Property set accfessor introduced in C#7.0
    • Methods introduced in C#6.0
    • Indexer introduced in C#7.0
The Syntax of expression body definition is,

member => expression;

where expression should be a valid expression and member can be any from above list of type members.
 
Suppose we have a method or constructor that contains a single expression or line of code. Then In spite of using the traditional way to write code inside a method or constructor code block, we can write them as a single syntax. Those members who can follow this approach are known as Expression Bodied Members.
 
Constructor
 
Expression Bodied technique can be used to define a constructor in a single statement. This can only be achieved if a constructor has only a single valid expression. A valid expression can be either assignment or a method call. If a constructor has more than one line of code or expression then this technique cannot be applied.
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             // Instance of Operations class created  
  10.             Operations ops = new Operations();  
  11.             Console.ReadLine();  
  12.         }  
  13.     }  
  14.   
  15.     class Operations  
  16.     {  
  17.         public int Num1 = 100;  
  18.         public int Num2 = 33;  
  19.   
  20.         // Constructor implemented using Expression Bodied  
  21.         // Expression or right side followed with => must be valid and should be one statement  
  22.         // Only assignment, call, increment, decrement, and new object expression can be used as a statement  
  23.         // This feature can only be used in C# 7.0 or onwards. Means In Visual Studio 2017 and onwards.  
  24.         // If we try to implement this feature in visual studio 2015 then the compiler will not             allow doing so and shows an error.  
  25.         public Operations()=> Num1= Num1+Num2;  
  26.   
  27. }  
  28. }  
In the above program, Expression bodied is used with the constructor. Expression or right side followed with '=>' must be valid and should be one statement. Only assignment, call, increment, decrement, and new object expression can be used as a statement. A constructor will be called whenever an instance of 'Operations' class is created. A constructor does not have any return type and it is private by default. We have performed addition between two numbers and assign its value to "Num1".
 
Some other examples of valid syntax are,
  • public Operation()=>Console.WriteLine("Value of Num1 is "+Num1+" and num2 is "+Num2);
  • public Operation()=>Num1= Num1+(100*Num2)/2;
Some other examples of invalid syntax are,
 
//Incorrect as it contains two statements. Produce error as Only assignment, call, increment, decrement, and new object expression can be used as a statement

public Operation()=>Console.WriteLine("Value of Num1 is "+Num1+" and num2 is "+Num2); Num1=Num1+Num2;
 
// Cannot declare a variable. Produce error as Only assignment, call, increment, decrement, and new object expression can be used as a statement

public Operation()=>int Num3= Num1+Num2;
 
//Cannot declare a variable. Produces error as only assignment, call, increment, decrement, and new object expression can be used as a statement

public Operation()=>int i;
 
Note

This feature is supported in C#7.0. So this feature can only be implemented in Visual Studio 2017 and onwards. If we try to implement this feature in visual studio 2015 then the compiler will not allow doing so and shows an error.
 
Destructor
 
Expression Bodied technique can be used to define Destructor in a single statement. A destructor is used to destruct the instances or release the resources used by the program and contain cleanup statements. This can only be achieved if Destructor has only a single valid expression. If Destructor has more than one line of code or expression then this technique cannot be applied.
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             // Instance of Operations class created  
  10.             Operations ops = new Operations();  
  11.             Console.ReadLine();  
  12.         }  
  13.     }  
  14.   
  15.     class Operations  
  16.     {  
  17.         public int Num1 = 100;  
  18.         public int Num2 = 33;  
  19.   
  20.         // Constructor implemented using Expression Bodied  
  21.         // This feature can only be used in C# 7.0 or onwards. Means In visual Studio 2017 and onwards.  
  22.         public Operations()=> Num1= Num1+Num2;  
  23.   
  24.         // Destructor implemented using Expression Bodied  
  25.         // Expression or right side followed with => must be valid and should be one statement  
  26.         // Only assignment, call, increment, decrement, and new object expression can be used as a statement  
  27.         // This feature can only be used in C# 7.0 or onwards. Means In visual Studio 2017 and onwards.  
  28.         // If we try to implement this feature in visual studio 2015 then compiler will will not allow to do so and shows an erro            r.  
  29.         ~Operations()=> Console.WriteLine("Destructor is called");  
  30. }  
  31. }  
In the above program, Expression bodied is used with destructor. Expression or right side followed with => must be valid and should be one statement. Only assignment, call, increment, decrement, and new object expression can be used as a statement. A destructor will be automatically called when the program exits. An instance is ready for destruction as soon as instance become useless. The destructor does not contain any return type or access modifier. We have written a line on the console.
 
Note

This Feature is supported in C#7.0. So this feature can only be implemented in Visual Studio 2017 and onwards. If we try to implement this feature in visual studio 2015 then the compiler will not allow doing so and shows an error.
 
Property get accessor
 
Expression Bodied technique can be used to define get accessor. Return keyword is not required for 'get' accessor.
  1. class Operations  
  2. {  
  3.     public int Num1 = 100;  
  4.     public int Num2 = 33;  
  5.     private string name;  
  6.   
  7.     // Property  
  8.     public string Name  
  9.     {  
  10.         // get accesor implemented by Expression Bodied  
  11.         get => name;  
  12.   
  13.     }  
  14. }  
In the above program, Expression bodied is used with Property get accessor. Expression or right side followed with => must be a valid single statement and must return a value of data type defined to property.
 
Note

Feature supported in C#6.0. So this feature can only be implemented in Visual Studio 2015 and onwards.
 
Property set accessor
 
Expression Bodied technique can be used to define set accessor. The expression should assign a value back to the variable of datatype defined to property.
  1. class Operations  
  2. {  
  3.     public int Num1 = 100;  
  4.     public int Num2 = 33;  
  5.     private string name;  
  6.   
  7.     // Property  
  8.   a   public string Name  
  9.     {  
  10.         // get accesor implemented by Expression Bodied  
  11.         get => name;  
  12.   
  13.         // set accesor implemented by Expression Bodied  
  14.         set => name = value;  
  15.         }  
  16.     }  
  17. }  
In the above program, Expression bodied is used with Property set accessor. Expression or right side followed with => must be valid single statement and must assign a value back to the variable of datatype defined to property.
 
Note

Feature suppoted in C#7.0. So this feature can only be implemented in visual Studio 2017 and onwards. If we try to implement this feature in visual studio 2015 then the compiler will not allow doing so and shows an error.
 
Method
 
Expression Bodied technique can be used to define method in a single statement. Single expression must return value of method's return type if method is not void type.
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             // Instance of Operations class created  
  10.             Operations ops = new Operations();  
  11.   
  12.             ops.Display();  
  13.             ops.called();  
  14.             ops.Addition(3, 44);  
  15.             ops.Compare(55, 66);  
  16.             Console.ReadLine();  
  17.         }  
  18.     }  
  19.   
  20.     class Operations  
  21.     {  
  22.         public int Num1 = 100;  
  23.         public int Num2 = 33;  
  24.   
  25.         // Method that will write on Console  
  26.         public void Display() => Console.WriteLine("Hello Buddy");  
  27.   
  28.         // Method that call another method  
  29.         public void called() => Display();  
  30.   
  31.         // Method that has two parameters and return their sum+100.  
  32.         // Return keyword is not required when implement method with Expression bodied  
  33.         public int Addition(int a, int b) => a + b + 100;  
  34.   
  35.         // Method that has two parameters and return value according to ternary operator condition.  
  36.         // Return keyword is not required when implement method with Expression bodied  
  37.         public int Compare(int a, int b) => a == b ? 100 : 200;  
  38.     }  
  39. }  
In the above program, Expression bodied is used with Method. Expression or right side followed with => must be valid statement. Only assignment, call, increment, decrement, and new object expression can be used as a statement. Also, statement must return value of methods's return type if method is not void type. Like we did in method Addition(int a, int b) whose return type is int type. return keyword is not required in this. This feature does not work if code block contains more than one statement.
 
Some other examples of invalid syntax are,
 
// compiler will produce an error as "Only assignment, call, increment, decrement, and new object expression can be used as a statement"

public void called() => int k;

//compiler will produce an error as "Invalid expression term 'int'"

public int Addition(int a, int b) => int c=a+b;

//compiler will produce an error as "Invalid expression term 'return'"

public int Compare(int a, int b) => return a == b? 100 : 200;
 
Note
Feature supported in C#6.0. So this feature can only be implemented in visual Studio 2015 and onwards.
 
Indexer
 
Expression Bodied technique can also be used to define set and get accessors of indexers.
  1. class Operations  
  2. {  
  3.     public int Num1 = 100;  
  4.     public int Num2 = 33;  
  5.   
  6.     public string[] Names = new string[5];  
  7.     public string this[int i]  
  8.     {  
  9.         get => Names[i];  
  10.   
  11.         set => Names[i] = value;  
  12.   
  13.     }  
  14. }  
In the above program, Expression bodied is used with Indexer get and set accessor. Similar to Property get and set acceesor.
 
Note

Feature suppoted in C#7.0. So this feature can only be implemented in Visual Studio 2017 and onwards. If we try to implement this feature in Visual Studio 2015 then the compiler will not allow doing so and shows an error.
 
Advantages and Disadvantages of Expression Bodied Members
  • Expression Bodied Members can be public, protected, internal, private and protected internal.
  • Expression Bodied Members can be declared virtual or abstract.
  • Expression Bodied Members can even override a base class method.
  • Expression Bodied Members can also be static.
  • Expression Bodied members require only one statement as expression. So block of code is not applicable with it.
  • Expression Bodied members do not support Loop(For, while, do while etc) but they can be replaced with LINQ.
  • Expression Bodied members does not support Conditional statements (if-else, nested if-else, switch etc) but if-else can be replaced with ternary operator.
Conclusion
 
Expression Bodied Members was introduced in C# 6.0 and later enhanced in C# 7.0. Expression Bodied Members decrease the line of code and increase the readability.I hope this article helps you to understand a bit more about Expression Bodied Members.
 
Thank you. Please feel free to ask any questions or make a suggestion.