In object-oriented software development, initializing objects is something we do all the time. In C#, the traditional way of defining constructors can get a bit repetitive, especially when you have to initialize lots of properties. To make this process cleaner and easier to read, C# 12 introduced primary constructors. In this post, we’ll explore what they are, how to use them, and why they can make your life easier.
What are primary constructors?
Primary constructors are a new syntax that lets you create and initialize objects in a more concise way. With them, you can define input parameters directly in the class declaration, and C# will automatically take care of assigning values to the properties. The idea is to reduce boilerplate code and improve readability.
Basic syntax
Before C# 12, constructors followed the traditional, more verbose structure. Here’s a classic example:
public class Person
{
public string Name { get; }
public int Age { get; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
In this version, you have to declare the constructor separately and manually assign values to each property inside it.
If you want your class to be immutable (i.e., properties are read-only), you can just use get without set, like in the example above. But if you want the properties to be mutable, just add set, and you can still initialize them using a primary constructor.
Now, with C# 12, you can do the same thing in a much shorter and cleaner way:
public class Person(string name, int age)
{
public string Name { get; } = name;
public int Age { get; } = age;
}
Here, name and age are declared directly in the class definition, and the properties are automatically initialized — no extra constructor block needed.
Working with inheritance
Primary constructors also work smoothly with inheritance, keeping things simple and clean. Here’s an example:
public class Person(string name, int age)
{
public string Name { get; } = name;
public int Age { get; } = age;
}
public class Employee(string name, int age, string department)
: Person(name, age)
{
public string Department { get; } = department;
}
In this case, Employee inherits from Person and adds a new property: Department. The constructor for Employee includes the parameters from the Person class, allowing us to pass values to the base constructor easily. Everything gets initialized in a clean and straightforward way — no extra noise in the code.
What we learned
Primary constructors in C# 12 offer a faster and cleaner way to create and initialize objects. Compared to the old-school constructor style, they make class definitions much easier to read and maintain. While there are some differences in how primary constructors behave in classes, records, and structs, this feature is definitely a great addition to your C# toolbox.
By understanding and using primary constructors, you can write code that’s not just more elegant, but also easier to maintain — and that’s a win in any project.