Available as part of Visual Studio 17.6 preview 2. C# will be adding primary constructors.
Primary constructors already exist (as such) for records, but can be added to classes and structs, so the syntax
public class Person(string firstName, string lastName, int age);
will be equivalent to
public class Person { private readonly string firstName; private readonly string lastName; private readonly int age; public Person(string firstName, string lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } }
By using a primary constructor the compiler will no longer generate a default (parameterless) constructor. You can ofcourse add your own but you’ll then need to call the primary constructor, for example
class Person(string firstName, string lastName, int age) { public Person() : this("", "", 0) { } }
An obvious syntactic difference between a class/struct primary constructor and a record’s is the record parameters are public, so we would tend to use property (Pascal Case) naming conventions and the properties are exposed as public readonly properties. For the class/struct these parameters map to private fields hence we use camel Case (if following the standards).
Note, you cannot access them using this.firstName. This statement might seem slightly confusing because whilst you cannot, for example, write the following
public Person() : this("", "", 0) { // this will not even compile this.firstName = "Test"; // also will not compile firstName = "Test"; }
You can do things like the following
class Person(string firstName, string lastName, int age) { public string FirstName { get => firstName; set => firstName = value; } public override string ToString() => $"{firstName} {lastName} {age}"; }
Essentially your primary constructor parameters are not available in overloaded constructors or using the this. syntax.