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?

  1. Where to Write It: You write the primary constructor right after the class or struct name inside parentheses.
  2. 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,

Why Use It?

Important Note

Some Limitations