#1,211 – C# 6.0 – Adding Implementation for a Primary Constructor
October 24, 2014 1 Comment
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; }
Pingback: Dew Drop – October 24, 2014 (#1884) | Morning Dew