Auto Property Initializer: A New Feature of C# 6.0

Introduction

On November 12, 2014, the day of the Visual Studio Connect() event, Microsoft announced Visual Studio 2015 Preview with many new and exciting features for developers for testing purposes. Microsoft announced the new version of C#, C# 6.0 that came with many improvements and new features. One of the newly introduced features of C# 6.0 is Auto Property Initializer.

Don't forget to read my previous posts on this series: "A new feature of C# 6.0"

What is an Auto Property Initializer.?

The Auto Property feature was first added to the C# language with the release of C# 3.0 on 19 November 2007 as a part of .NET Framework 3.5 that allows us to define the property without any backing field, however we still need to use constructors to initialize these auto properties to a non-default value. With the release of C# 6.0, a new feature called Auto Property Initializer allows us to initialize these properties without a constructor. In C# 6.0, we can now initialize the properties where they are declared.

Example 1

The following code snippet defines a class Student with one auto property, Name, and a parameterized constructor has been defined to initialize this property to some value.

public class Student
{
    public string Name { get; set; } // auto property - Name declaration

    public Student() // constructor
    {
        Name = "Akash"; // assignment
    }
}

Note that

  • Both the declaration and assignment are in different places.
  • We can't have a "get" only auto-property.

In C# 6.0, the same code can be rewritten as shown below.

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

What is Getter Only Auto-Properties?

Properties can be made read-only by removing the setter accessor. That can be done by having only a get accessor in the property implementation. With no setter, immutability is easier to do.

Example 2

The following code only has a getter accessor.

public class Point
{   
    public int x { get; }   
    public int y { get; }   
}

Example 3

To make the set accessor available only to code within the class, we can use the private access modifier. The property will appear to be read-only when accessed from outside of the defined (where the property is defined with a private set accessor) class.

  • When the declaration and assignment of the get accessor and set accessor are in a single class, we can easily initialize the values using the setter accessor in that class.
    using System;
    namespace CSharpFeatures
    {
        public class AutoProperty
        {
            public string Name { get; private set; } = "Amit Sharma";
    
            public static void Main(string[] args)
            {
                AutoProperty ap = new AutoProperty();
                ap.Name = "Abhishek Arora";
                Console.WriteLine("Name= {ap.Name}"); // prints Abhishek Arora
                Console.ReadKey();
            }
        }
    }
    
  • When the declaration and assignment of the get accessor and set accessor are in a different class we are unable to initialize the values using a setter accessor in another class except where they are declared.
    using System;
    namespace CSharpFeatures
    {
        public class AutoProperty
        {
            public string Name { get; private set; } = "Amit Sharma";
        }
    
        public class exec
        {
            public static void Main(string[] args)
            {
                AutoProperty ap = new AutoProperty();
                ap.Name = "Abhishek Arora";                  // Error   
                Console.WriteLine("Name= \{ap.Name}");
                Console.ReadKey();
            }
        }
    }
    
    Setter inaccessible

Demo Application using Visual Studio 2013.

using System;
namespace CSharpFeatures
{
    public class Studentdetails
    {
        private string _name;

        public string Name
        {
            get { return this._name; }
            set { this._name = value; }
        }
        private string _address;
        public string Address
        {
            get { return this._address; }
            set { this._address = value; }
        }
        public static void Main(string[] args)
        {
            Studentdetails Student1 = new Studentdetails();
            Student1.Name = "Amit Sharma";
            Student1.Address = "Delhi";
            Console.WriteLine("\n Student1");
            Console.WriteLine(" Name= {0}", Student1.Name);
            Console.WriteLine(" Address= {0}", Student1.Address);
            Studentdetails Student2 = new Studentdetails
            {
                Name = "Vijay Verma",
                Address = "New Delhi"
            };

            Console.WriteLine("\n Student2");
            Console.WriteLine(" Name= {0}", Student2.Name);
            Console.WriteLine(" Address= {0}", Student2.Address);
            Console.ReadKey();
        }
    }
}

Output

Property

Demo Application using Visual Studio 2015 Preview.

using System;
namespace CSharpFeatures
{
    public class Studentdetails
    {
        public string Name { get; set; } = "Amit Sharma";
        public string Address { get; set; } = "Delhi";

        public static void Main(string[] args)
        {
            Studentdetails Student1 = new Studentdetails();
            Console.WriteLine(nameof(Student1));
            Console.WriteLine(" Name= \{Student1.Name}");
            Console.WriteLine(" Address= \{Student1.Address} ");
            Studentdetails Student2 = new Studentdetails
            { Name = "Vijay Verma", Address = "New Delhi" };
            Console.WriteLine("\n");
            Console.WriteLine(nameof(Student2));
            Console.WriteLine(" Name= \{ Student2.Name}");
            Console.WriteLine(" Address= \{ Student2.Address} ");
            Console.ReadKey();
        }
    }
}

Output

VS15 output

Summary

In this article, we learned how to initialize the Auto Property Initializer without using a constructor and can be initialized where they are declared. I hope you liked this feature of C# 6.0. Don't forget to read my other articles on the series " A new feature of C# 6.0". Share your opinion about this feature and how will you use it in your project. Your comments are most welcome. Happy Coding!


Similar Articles