Search code examples
c#language-features

What exactly are the "auto-implemented properties" introduced in C# 6.0?


Microsoft's version history page mentions "auto-implemented properties" as one of the new features added to C# in version 6.

Their page on auto-implemented properties gives the following code example:

public class Customer
{
    // Auto-implemented properties for trivial get and set
    public double TotalPurchases { get; set; }
    public string Name { get; set; }
    public int CustomerId { get; set; }
    ...
}

I have just encountered some very old code running on C# version 5.0. I can verify it is running on version 5 because it fails to build if I attempt to add in string interpolation ($"{x}") or null the coalescing operator (x?.y), both other features added in 6.0.

However, if I add code similar to the example above, it works. In particular, this complete program works as expected, and prints out "other text2".

public class Program
{
    static void Main(string[] args)
    {
        var x = new Foo
        {
            Bar = "text"
        };

        x.Bar = "other text";
        var y = x.Bar + "2";
        Console.WriteLine(y);
    }
}

public class Foo
{
    public string Bar { get; set; }
}

So, what exactly is the feature that you have access to in C# 6.0 that is lacking in 5.0, which the version history refers to as "auto-implemented properties"? Or, alternatively, is there some reason that despite running with a LangVersion of 5.0, I would be able to use auto-implemented properties but not null coalescing, string interpolation, and other features from C# 6?


Solution

  • Microsoft's version history page mentions "auto-implemented properties" as one of the new features added to C# in version 6.

    That's not what it says. It was "auto-property initialisers" that was added. Auto-implemented properties (or auto-properties for short) were added in C# 3.

    The example shown at the start of the auto-properties programming guide page does not use auto-property initialisers, which is why you can still compile the code in C# 5.

    However, further down that page, it says:

    You can initialize auto-implemented properties similarly to fields:

    public string FirstName { get; set; } = "Jane";
    

    That was new in C# 6. Before, you had to do it in a constructor if you wanted to initialise auto-properties to a custom value:

    public class Person {
        public string FirstName { get; set; }
    
        public MyClass() {
            FirstName = "John";
        }
    }