Expression-bodied members - C# 6 Language New features

Visual studio 2015 released with drastic changes in C# 6. As a developer, I notice one thing. Microsoft had embellished C# 6 with new syntax. It will not only make your code clean, but also reduce line of code. 

Today, I am going to explore another useful feature "Expression bodied members". Expression bodied members is C# 6 new fundamental feature that simplified code using lambda expressions. Expression bodied member feature use lambda expression instead of statement blocks.
Expression-Bodied for Get-only Properties
If your class has any get only property, you'll be able to use lambda expression syntax instead of statement blocks. In our example, I have to write whole statement block (may be now you can call it traditional syntax), if I want sum of Val1 and Val2.
public class Calculator
{
    public int Val1 { get; set; }
    public int Val2 { get; set; }

    public int Sum
    {
        get
        {
            return Val1 + Val2;
        }
    }
}
In C# 6 Microsoft make it pretty simple using new lambda expression syntax. I write same example with new Expression bodied syntax.
public class Calculator
{
    public int Val1 { get; set; }
    public int Val2 { get; set; }
    public int Sum => Val1 + Val2;
}

Expression-Bodied for Methods
Let's start with Expression Bodied with methods. I have calculator class having method named Sum. In our example, I wrote a simple method code block to sum of two variables. I pass two parameters and return the sum of parameters.
public class Calculator
{
    public int Val1 { get; set; }
    public int Val2 { get; set; }

    public int Sum(int val1, int val2)
    {
        return val1 + val2;
    }
}
As per new expression syntax, Lambda expression syntax is concise way to declare a method that's remove unwanted code blocks and return the sum without any return statement.
public class Calculator
{
    public int Val1 { get; set; }
    public int Val2 { get; set; }
    public int Sum(int val1, int val2) => val1 + val2;
}

Though expression bodied members have several limitations(not even support if-else or switch), it's useful to scale back burden of syntax.

Comments

Popular posts from this blog

12 opensource and free asp.net MVC gridview contols

Scheduling background jobs using Hangfire in ASP.NET Core

Difference ExecuteNonQuery vs ExecuteScalar vs ExecuteReader in asp.net