C# 6 Preview: Expression-bodied members

C# 6 is expected to simplify writing properties and methods that involve a single expression. Consider this property exposing a backing field, for instance:

        private string firstName;

        public string FirstName
        {
            get
            {
                return this.firstName;
            }
        }

We may now write this as:

        private string firstName;

        public string FirstName => firstName;

And this is also quite handy for more complex properties:

        public string FullName => string.Format("{0} {1}", this.firstName, this.lastName);

It works pretty nicely with indexers, even though the C# feature descriptions (PDF) document says it shouldn’t work in the current CTP:

    public class Inventory
    {
        private string[] inventory = new string[10];

        public string this[int index] => this.inventory[index];

        public void Put(int index, string item)
        {
            this.inventory[index] = item;
        }
    }

The expression-bodied members feature gives you a pretty convenient way to write getter-only properties. However, this syntax isn’t restricted to properties alone; you can also use it with methods. The following examples are from the official C# feature descriptions (PDF):

public Point Move(int dx, int dy) => new Point(x + dx, y + dy);

public static Complex operator +(Complex a, Complex b) => a.Add(b);

public static implicit operator string(Person p) => p.First + " " + p.Last;

void methods, which don’t return anything, may also take advantage of this syntax. In fact, we can quite easily rewrite the Inventory class’s operations using expression-bodied methods:

    public class Inventory
    {
        private string[] inventory = new string[10];

        public string this[int index] => this.inventory[index];

        public void Put(int index, string item) => this.inventory[index] = item;
        public void RemoveAt(int index) => this.inventory[index] = null;
    }

You can appreciate how this can make classes much more concise.

Leave a Reply

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