Wednesday, January 7, 2015

C# 6.0–Expression Bodied Members

This blog post is part of C# 6.0 Features Series.
There are lots of great features added to C# 6.0 and Expression bodied members are one of them. It’s provide great syntax sugar which will help you make your code more beautiful and readable.  In earlier versions of C# type definitions were always been tedious and we need to provide a curly braces and return type even if that function contains one single line. Expression bodied function will help you in such scenarios.

Let’s take a example to understand it. Following is a code to understand it.
using System;

namespace ExpressionBodiedMemebers
{
    class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person
            {
                FirstName = "Jalpesh",
                LastName = "Vadgama"
            };
            Console.WriteLine(person.GetFullName());
        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public string GetFullName()
        {
            return string.Format("{FirstName} {LastName}");
        }
    }
}

Here you can see that I have created person class which has two property FirstName and LastName and a method GetFullName returns string with combination of  FirstName and LastName. And in main method I have created object of Person class and printed FullName of person. Now let’s write that in new way with Expression Bodied Members like following.
using System;

namespace ExpressionBodiedMemebers
{
    class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person
            {
                FirstName = "Jalpesh",
                LastName = "Vadgama"
            };
            Console.WriteLine(person.GetFullName());
        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public string GetFullName() => string.Format("\{FirstName} \{LastName}");
    }
}
Now if you see the above code you can see that for GetFullName function we don't need to write curly braces and return statement and we can do it like just like lamda expression. This make code more beautiful and readable.

Now let’s run that code and output is as expected.

csharp6-expression-bodied-function

That’s it. Hope you like it. Stay tuned for more!!

You can find all the example of  C# 6.0 new features on this blog  on github  at following location
https://github.com/dotnetjalps/Csharp6NewFeatures
Share:

0 comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews