Auto Property Enhancements in C# 6

Automatic properties were introduced in C# 3 which made it easier to declare properties without explicitly specifying the private backing field.
Before

private string name;
public string Name
{
    get { return name; }
    set { name = value; }
}

Automatic Property

public string Name { get; set; }

But still there is a problem with this implementation. We cannot assign a default value to a property created using automatic property syntax and requires private field to be declared.
C# 6 addresses this problem and added a provision to initialize an auto-implemented property.

Initializer for auto-properties

public class Student
    {
        public string Name { get; set; } = "Jack";
    }

The initializer declares and assigns the backing private backing field for you.

Getter only auto-properties

Before C# 6 if you try to declare a property like following

public class Person
    {
        public string Name { get; }
    }

You will get a compilation error as “Person.Name.get must declare a body because it is not marked abstract or extern. Automatically implemented properties must define both get and set accessors.
C# 6 allows auto-properties to be declared without a setter. The backing field of getter only auto-property is implicitly declared as readonly. It’s value can be assigned in type’s constructor too.

public class Person
    {
        public string Name { get; }
        public Person(string firstName,string lastName)
        {
            Name = string.Format("{0} {1}", firstName, lastName);
        }
    }

Auto property initializers work for getter only properties also.

public class Person
    {
        public string Name { get; } = "Jack";
    }

Thanks for reading this post. Read more on all C# 6 features.

You may also like...