C# 6 Auto-Property Initializers

C# 6 Auto-Property Initializers

C# 6 includes auto-property initializers, which are a handy way to set initial property values on auto-implemented properties. Auto-property initializers are basically a shortcut to setting the property value in the constructor. I wasn't overly excited about the new feature at first, but I think it makes the intention a lot more clear when you see the initial value on the same line as the auto-implemented property.

Auto-Property Initializers in C# 6

Before C# 6 you might have set the initial value of an auto-implemented property as follows:

public class ToDo {
    public string Title { get; set; }

    public ToDo() {
        Title = "New ToDO";
    }
}

In C# 6 you can declare the auto-implemented property and initial value as a single declaration:

public class ToDo {
    public string Title { get; set; } = "New ToDo";
}

I find it a lot easier to read and understand the intention with the new auto-property initializer in C# 6.

Conclusion

I will write additional C# 6 tutorials in the future as well as tutorials on ASP.NET 5, ASP.NET MVC 6, and Orchard CMS. You can also find me on twitter.