C# 6 features – Expression-bodied members

Expression-bodied members

facebooktwittergoogle_pluslinkedinmail

Expression bodied functions were created to provide simplified syntax for cases where implementation is straightforward. They improve C# code readability significantly.

Expression-bodied function members improves methods and properties declaration. Instead of statement blocks it’s now possible to define body as lambda expression. The syntax is quite easy – use the same lambda arrow (=>).

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

        public string FullName => $"{FirstName} {LastName}";

        public override string ToString() => FullName;
    }

Note usage of another C# 6 feature (string interpolation) in the above example.

FullName property is a getter-only property, although there is no get keyword used – it’s implied by use of the expression body syntax.

Each expression-bodied function is compiled the same as if it was a block body with single return statement. The above example is compiled to something like this:

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

        public string FullName
        {
            get
            {
                return $"{FirstName} {LastName}";
            }
        }

        public override string ToString()
        {
            return FullName;
        }
    }

Yep, the expression-bodied example is much easier to read and understand.

 

Void returning methods

For void returning methods and async methods (returns Task) the arrow syntax stays but expression must be statement expression (void return).

        public void Print() => Console.WriteLine(FullName);
        public async void PrintAsync() => await Task.Run(() => Print());

 

Index methods

The same as properties and regular methods, indexers can have expression body.

        public Person this[Guid id] => FindPerson(id);

 

facebooktwittergoogle_pluslinkedinmail

Leave a comment

Your email address will not be published. Required fields are marked *