#1,210 – C# 6.0 – Primary Constructors

NOTE: Primary constructors will not be shipping in C# 6.0, after all.  They were implemented in the language, but did not yet have appropriate downstream work done in time for the release of 6.0 (i.e. in Visual Studio and debugger).  Thanks to Steve Hall for pointing this out.  –SPS, 23Oct14

C# 6.0 introduces the notion of a primary constructor–a constructor defined as part of the type declaration, rather than as a separate method.

Consider the C# 5.0 example below, with a traditional constructor that initializes a couple of properties.  (Note that Name property is not immutable, but only protected).

    public class Dog
    {
        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public string Name { get; protected set; }
        public int Age { get; set; }
    }

The primary constructor syntax allows us to simplify this code, moving the constructor into the class declaration.  We can then use auto-property initializers that reference the constructor’s parameters.

    public class Dog(string name, int age)
    {
        public string Name { get; protected set; } = name;
        public int Age { get; set; } = age;
    }

This second code fragment behaves exactly like the first.

Advertisement