C# 7.0 – Expression-bodied members


Facebooktwittergoogle_pluslinkedinmail

Expression bodied members were a very popular feature of C# 6.0. Unfortunately, their usage was limited only to methods and properties.

Note: You can view all code examples on GitHub. My environment: Visual Studio 2017 and .NET Framework 4.6.1.

Expression-bodied constructor

C# 7.0 allows defining a constructor with expression body.

using System;

namespace CSharp7.ExpressionBodiedMembers
{
    class Example1
    {
        public Example1() => Console.WriteLine("Expression-bodied constructor");
    }
}

Expression-bodied finalizer

The new C# version allows also to define a finalizer with expression body.

using System;

namespace CSharp7.ExpressionBodiedMembers
{
    class Example2
    {
        ~Example2() => Console.WriteLine("Expression-bodied finalizer");
    }
}

Extended expression-bodied properties

C# 6.0 makes it possible to define expression-bodied properties, but they were getter-only properties.

using System;

namespace CSharp7.ExpressionBodiedMembers
{
    class Example3
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

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

With C# 7.0 a property getter and setter can be defined with expression body separately.

using System;

namespace CSharp7.ExpressionBodiedMembers
{
    class Example4
    {
        private string _name;

        public string Name
        {
            get => _name;
            set => _name = value ?? "";
        }
    }
}

 

Facebooktwittergoogle_pluslinkedinmail

Leave a comment

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