#1,211 – C# 6.0 – Adding Implementation for a Primary Constructor

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

A primary constructor in C# 6.0 allows declaring constructor parameters as part of the type declaration and then using those parameters within auto-property initializers.

You can optionally include an implementation body for the primary constructor, typically at the start of the type.  The implementation includes a code block without any method name or parameters.

Below, the primary constructor implementation derives the value of one property from the name parameter and does some validation on the age parameter.

    public class Dog(string name, int age)
    {
        {
            Name = name + " the Dog";
            if (age > 20)
                throw new ArgumentException("Age too large");
        }

        public string OrigName { get; } = name;
        public string Name { get; protected set; }
        public int Age { get; set; } = age;
    }

1211-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #1,211 – C# 6.0 – Adding Implementation for a Primary Constructor

  1. Pingback: Dew Drop – October 24, 2014 (#1884) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: