Expression Bodied Members: A New Feature of C# 6.0

Introduction

On November 12, 2014, the day of Visual Studio Connect() event, Microsoft announced Visual Studio 2015 Preview with many new and exciting features for developers for testing purposes. Microsoft announced the new version of C#, C# 6.0 that came with many improvements and new features. One of the newly introduced features of C# 6.0 is Expression Bodied Members.

Don't forget to read my previous posts on this series: "A new feature of C# 6.0".

    What are Expression Bodied Members

    Expression bodied members is another feature of C# 6.0 that simplifies the syntactic expression in C# programming. The main advantage of using the Expression bodied members is to reduce the source code by creating the expression bodies for the function/method and property. Since we are already familiar with Lambda expressions, the expression bodied members extend the similar use of lambda expressions for methods/functions, properties.

    Sometimes we create functions with not more than 3 or 4 lines of code for performing an activity like printing or conversion, using expression bodies we can reduce the number of lines of source code without using any {} curly braces. In other words we can use => (lambda arrow) instead of the old {} (curly braces) that is just like a new formatting tool. The following code snippet will tell us how to use a lambda arrow (=>) to shorten our source code.

    1. public string GetFullDetails() => string.Format("\n Name: \{Name}\n Age: \{Age}");  

    lambda arrow

    Expression bodied methods

    The following code block shows, we have a LeapYear() method that returns whether a year is a leap year or not and prints it in the console. This is what we do typically until now.

    • Using C# 5.0

      1. using System;  
      2. namespace CSharpFeatures  
      3. {  
      4.     class LeapYearProgram  
      5.     {  
      6.         public static int year = 2016;  
      7.         static void Main(string[] args)  
      8.         {  
      9.             Console.WriteLine(LeapYear());  
      10.             Console.ReadKey();  
      11.         }  
      12.         public static string LeapYear()  
      13.         {  
      14.             return "\n Is " + year + " a leap year- " + DateTime.IsLeapYear(year); // Prints True  
      15.         }  
      16.     }  
      17. }  
    • With the use of C# 6.0, Expression Bodied Methods, we can use the Lambda expression for the method definition part.

      1. using System;  
      2. using System.Console;  
      3. namespace CSharpFeatures  
      4. {  
      5.     class LeapYearProgram  
      6.     {  
      7.         public static int year = 2016;  
      8.         static void Main(string[] args)  
      9.         {  
      10.             WriteLine(LeapYear());  
      11.             ReadKey();  
      12.         }  
      13.         public static string LeapYear() => "\n Is \{year} a leap year:- " + DateTime.IsLeapYear(year); //Prints True  
      14.     }  
      15. }  

    Output

    Both of the preceding code snippets will give us the same output.

    method expression bodied

    Expression bodied properties

    We can also implement getter only (read only) properties using expression bodied properties. For example now in C# 6.0, instead of writing the entire property body using a getter, we can now just use a lambda arrow (=>) to return values. The following code returns "Amit Sharma " when you access the property " Name ".

    • In C# 5.0

      1. using System;  
      2. public class propertexample  
      3. {  
      4.     public string Name  
      5.     {  
      6.         get { return "Amit Sharma"; }  
      7.     }  
      8.     public static void Main(string[] args)  
      9.     {  
      10.         propertexample ap = new propertexample();  
      11.         Console.WriteLine("\n Name= {0}", ap.Name);  // prints Amit Sharma  
      12.         Console.ReadKey();  
      13.     }  
      14. }   
    • In C# 6.0

      1. using System;  
      2. using System.Console;  
      3. namespace CSharpFeatures  
      4. {  
      5.     public class propertexample  
      6.     {  
      7.         public string Name => "Amit Sharma";  
      8.         public static void Main(string[] args)  
      9.         {  
      10.             propertexample ap = new propertexample();  
      11.             WriteLine("\n Name= \{ap.Name}");  // prints Amit Sharma  
      12.             ReadKey();  
      13.         }  
      14.     }  
      15. }   

    Output

    Both of the preceding code snippets will give us the same output.

    method expression property

    Demo Application using Visual Studio 2013

    1. using System;  
    2. using System.Threading;  
    3. namespace CSharpFeatures  
    4. {  
    5.     public class ExpressionBodied  
    6.     {  
    7.         public int squarearea(int side)  
    8.         {  
    9.             return side * side;  
    10.         }  
    11.         public int operations(int a, int b)  
    12.         {  
    13.             return ((a + b) + (a - b) + (a * b) + (a / b));  
    14.         }  
    15.         public double squareroot(int X, int Y)  
    16.         {  
    17.             return Math.Sqrt(X * X + Y * Y);  
    18.         }  
    19.     }  
    20.     public class main  
    21.     {  
    22.         static void Main()  
    23.         {  
    24.             ExpressionBodied EB = new ExpressionBodied(); // Creating object of ExpressionBodied class  
    25.             Console.Write("\n -- Calculating Area of Square -- ");  
    26.             Console.Write("\n Enter side of the square: ");  
    27.             int i = Convert.ToInt32(Console.ReadLine());  
    28.             int sa = EB.squarearea(i);  
    29.             Thread.Sleep(2000);  //"Sleep for 2 seconds"  
    30.             Console.WriteLine(" Area of Square is {0}", sa);  
    31.   
    32.             Console.WriteLine("\n -- Calculating an Arithmatic Operation -- ");  
    33.             Console.Write(" Enter the value of a: ");  // Entering value a  
    34.             int x = Convert.ToInt32(Console.ReadLine());  
    35.             Console.Write(" Enter the value of b: ");  // Entering value b  
    36.             int y = Convert.ToInt32(Console.ReadLine());  
    37.             int op = EB.operations(x, y);  
    38.             Thread.Sleep(2000);  // "Sleep for 2 seconds"  
    39.             Console.WriteLine(" Result of the operation performed is {0}", op);  
    40.   
    41.             Console.WriteLine("\n -- Calculation Square Root --");  
    42.             Console.Write(" Square Root of sides 3 and 4 is: ");  
    43.             double sq = EB.squareroot(3, 4);  
    44.             Thread.Sleep(2000);  // "Sleep for 2 seconds"  
    45.             Console.Write(sq);  
    46.             Console.ReadKey();  
    47.         }  
    48.     }  
    49. }  

    Output

    VS13 Output

    Demo Application using Visual Studio 2015 Preview

    1. using System;  
    2. using System.Console;  
    3. using System.Convert;  
    4. using System.Threading;  
    5. namespace CSharpFeatures  
    6. {  
    7.     public class ExpressionBodied  
    8.     {  
    9.         public int squarearea(int side) => side * side;  
    10.         public int operations(int a, int b) => ((a + b) + (a - b) + (a * b) + (a / b));  
    11.         public double squareroot(int X, int Y) => Math.Sqrt(X * X + Y * Y);  
    12.     }  
    13.     public class main  
    14.     {  
    15.         static void Main()  
    16.         {  
    17.             ExpressionBodied EB = new ExpressionBodied(); // Creating object of ExpressionBodied class  
    18.             Write("\n -- Calculating Area of Square -- ");  
    19.             Write("\n Enter side of the square: ");  
    20.             int i = ToInt32(ReadLine());  
    21.             int sa = EB.squarearea(i);  
    22.             Thread.Sleep(2000);  //"Sleep for 2 seconds"  
    23.             Write(" Area of Square is \{sa}\n\n");  
    24.   
    25.             WriteLine("\n -- Calculating an Arithmatic Operation -- ");  
    26.             Write(" Enter the value of a: ");  // Entering value a  
    27.             int x = ToInt32(ReadLine());  
    28.             Write(" Enter the value of b: ");  // Entering value b  
    29.             int y = ToInt32(ReadLine());  
    30.             int op = EB.operations(x, y);  
    31.             Thread.Sleep(2000);  // "Sleep for 2 seconds"  
    32.             WriteLine(" Result of the operation performed is \{op}");  
    33.   
    34.             WriteLine("\n -- Calculation Square Root --");  
    35.             Write(" Square Root of sides 3 and 4 is: ");  
    36.             double sq = EB.squareroot(3, 4);  
    37.             Thread.Sleep(2000);  // "Sleep for 2 seconds"  
    38.             Write(sq);  
    39.             Read();  
    40.         }  
    41.     }  
    42. }  

    Output

    VS15 Output

    Summary

    In this article we learned about Expression Bodied Members, the new feature of C# 6.0. Though it is still not very clear what additional benefits it will provide, but it will definitely give us clean code by reducing some code, brackets and so on. What additional benefits do you think there are? Please comment and share with us. Don't forget to read my other articles on the series "A new feature of C# 6.0". Share your opinion about this feature and how will you use it in your project? Your comments are most welcome. Happy Coding!


    Similar Articles