Expression Bodied Members: A New Feature of C# 6.0

Introduction

On November 12, 2014, the day of the 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, and 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) which 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.

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
    using System;  
    namespace CSharpFeatures  
    {  
        class LeapYearProgram  
        {  
            public static int year = 2016;  
            static void Main(string[] args)  
            {  
                Console.WriteLine(LeapYear());  
                Console.ReadKey();  
            }  
            public static string LeapYear()  
            {  
                return "\n Is " + year + " a leap year- " + DateTime.IsLeapYear(year); // Prints True  
            }  
        }  
    }  
  • With the use of C# 6.0, Expression Bodied Methods, we can use the Lambda expression for the method definition part.

    using System;  
    using System.Console;  
    namespace CSharpFeatures  
    {  
        class LeapYearProgram  
        {  
            public static int year = 2016;  
            static void Main(string[] args)  
            {  
                WriteLine(LeapYear());  
                ReadKey();  
            }  
            public static string LeapYear() => "\n Is \{year} a leap year:- " + DateTime.IsLeapYear(year); //Prints True  
        }  
    }  

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

    using System;  
    public class propertexample  
    {  
        public string Name  
        {  
            get { return "Amit Sharma"; }  
        }  
        public static void Main(string[] args)  
        {  
            propertexample ap = new propertexample();  
            Console.WriteLine("\n Name= {0}", ap.Name);  // prints Amit Sharma  
            Console.ReadKey();  
        }  
    }   
  • In C# 6.0

    using System;  
    using System.Console;  
    namespace CSharpFeatures  
    {  
        public class propertexample  
        {  
            public string Name => "Amit Sharma";  
            public static void Main(string[] args)  
            {  
                propertexample ap = new propertexample();  
                WriteLine("\n Name= \{ap.Name}");  // prints Amit Sharma  
                ReadKey();  
            }  
        }  
    }   

Output

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

method expression property

Demo Application using Visual Studio 2013

using System;
using System.Threading;
namespace CSharpFeatures
{
    public class ExpressionBodied
    {
        public int squarearea(int side)
        {
            return side * side;
        }
        public int operations(int a, int b)
        {
            return ((a + b) + (a - b) + (a * b) + (a / b));
        }
        public double squareroot(int X, int Y)
        {
            return Math.Sqrt(X * X + Y * Y);
        }
    }
    public class main
    {
        static void Main()
        {
            ExpressionBodied EB = new ExpressionBodied(); // Creating object of ExpressionBodied class
            Console.Write("\n -- Calculating Area of Square -- ");
            Console.Write("\n Enter side of the square: ");
            int i = Convert.ToInt32(Console.ReadLine());
            int sa = EB.squarearea(i);
            Thread.Sleep(2000); //"Sleep for 2 seconds"
            Console.WriteLine(" Area of Square is {0}", sa);
            Console.WriteLine("\n -- Calculating an Arithmetic Operation -- ");
            Console.Write(" Enter the value of a: "); // Entering value a
            int x = Convert.ToInt32(Console.ReadLine());
            Console.Write(" Enter the value of b: "); // Entering value b
            int y = Convert.ToInt32(Console.ReadLine());
            int op = EB.operations(x, y);
            Thread.Sleep(2000); // "Sleep for 2 seconds"
            Console.WriteLine(" Result of the operation performed is {0}", op);
            Console.WriteLine("\n -- Calculation Square Root --");
            Console.Write(" Square Root of sides 3 and 4 is: ");
            double sq = EB.squareroot(3, 4);
            Thread.Sleep(2000); // "Sleep for 2 seconds"
            Console.Write(sq);
            Console.ReadKey();
        }
    }
}

Output

VS13 Output

Demo Application using Visual Studio 2015 Preview

using System;  
using System.Console;  
using System.Convert;  
using System.Threading;  
namespace CSharpFeatures  
{  
    public class ExpressionBodied  
    {  
        public int squarearea(int side) => side * side;  
        public int operations(int a, int b) => ((a + b) + (a - b) + (a * b) + (a / b));  
        public double squareroot(int X, int Y) => Math.Sqrt(X * X + Y * Y);  
    }  
    public class main  
    {  
        static void Main()  
        {  
            ExpressionBodied EB = new ExpressionBodied(); // Creating object of ExpressionBodied class  
            Write("\n -- Calculating Area of Square -- ");  
            Write("\n Enter side of the square: ");  
            int i = ToInt32(ReadLine());  
            int sa = EB.squarearea(i);  
            Thread.Sleep(2000);  //"Sleep for 2 seconds"  
            Write(" Area of Square is \{sa}\n\n");  
  
            WriteLine("\n -- Calculating an Arithmatic Operation -- ");  
            Write(" Enter the value of a: ");  // Entering value a  
            int x = ToInt32(ReadLine());  
            Write(" Enter the value of b: ");  // Entering value b  
            int y = ToInt32(ReadLine());  
            int op = EB.operations(x, y);  
            Thread.Sleep(2000);  // "Sleep for 2 seconds"  
            WriteLine(" Result of the operation performed is \{op}");  
  
            WriteLine("\n -- Calculation Square Root --");  
            Write(" Square Root of sides 3 and 4 is: ");  
            double sq = EB.squareroot(3, 4);  
            Thread.Sleep(2000);  // "Sleep for 2 seconds"  
            Write(sq);  
            Read();  
        }  
    }  
}  

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