A Primary Constructor is a new way to write constructors in C# 12 that makes your code shorter and easier to read.
How Does It Work?
- Where to Write It: You write the primary constructor right after the class or struct name inside parentheses.
- Using Parameters: The parameters you define in the primary constructor can be used throughout the class or struct.
For example, you can declare a class with a primary constructor like this.
public class Student(string name, int age)
{
// primary constructor parameters are in scope here
}
The primary constructor parameters name and age are not public properties, but they can be used to initialize public properties like this.
public class Student(string name, int age)
{
public string Name { get; } = name; // initialize a readonly property
public int Age { get; set; } = age; // initialize a read-write property
}
You can also use primary constructor parameters to call a base constructor like this.
public class Alumni(string name, int age, string school) : Student(name, age)
{
public string School { get; } = school;
}
In this example,
- Student is a class with a primary constructor that takes name and age as parameters.
- These parameters are used to set the values of the properties Name and Age.
Why Use It?
- Less Code: You don’t need to write a separate constructor method.
- Clearer Code: It’s easier to see what the class needs to be created.
Important Note
- If you use a primary constructor, the class won’t have a default (parameterless) constructor unless you add one yourself.
Some Limitations
- Primary constructor parameters are not stored as fields unless they are needed. This means they do not consume memory or affect the size of the type.
- Primary constructor parameters are not members of the type. This means you cannot access them using this or base or use them in attribute arguments or default parameter values.
- Primary constructor parameters can be assigned to them, but they are not properties. This means they do not have getters or setters, and they do not support attributes or modifiers.
- Primary constructor parameters are only available in the type where they are declared. This means derived types do not inherit them and are not visible to external callers.
- Every other constructor for a class must call the primary constructor, directly or indirectly, through this() constructor invocation. This ensures that primary constructor parameters are always assigned and available in the type.