Primary constructors have been around for record types for a while, and they're one of the reasons records feel so concise. With C# 12 and .NET 8, the same syntax became available for regular classes and structs.
It looks like a small change, but it comes with a few surprises. Primary constructor parameters in classes don't behave like record properties, and they don't behave like readonly fields either.
In this article, we'll compare primary constructors in records, classes, and structs, look at what the compiler generates behind the scenes, see how they work with dependency injection, and go through the pitfalls you should know about before using them everywhere.
Let's dive in!
Records and Their Primary Constructors
Let's start with the version we already know:
public record Dimensions(int Width, int Height);
With this single line, we create a record type called Dimensions. For the Width and Height parameters, the compiler generates two public properties behind the scenes. For a record class, they're init-only, so they can only be set when we create the object. For a record struct, they're regular read-write properties, unless we mark it as readonly record struct.
This is a very simple, yet vital feature. With it, we save a lot of time and effort when creating records. Keep the "public properties" part in mind, as this is exactly where classes and structs work differently.
Primary Constructors for Classes
Before we see how primary constructors work for classes, let's take a look at a simple, old-fashioned class:
public class BankAccount
{
private readonly string _accountNumber;
public decimal Balance { get; set; }
public BankAccount(string accountNumber, decimal balance)
{
_accountNumber = accountNumber;
Balance = balance;
}
public void Deposit(decimal amount)
{
Balance += amount;
Console.WriteLine($"Deposited {amount:C} to {_accountNumber}. New balance: {Balance:C}");
}
public void Withdraw(decimal amount)
{
if (amount <= Balance)
{
Balance -= amount;
Console.WriteLine($"Withdrawn {amount:C} from {_accountNumber}. New balance: {Balance:C}");
}
else
{
Console.WriteLine($"Insufficient funds on {_accountNumber}.");
}
}
}
We have a class called BankAccount. Its constructor takes in two arguments: the account number and the balance. For the account number, we have a private readonly field, and for the balance, we have a dedicated property. We also have two methods for depositing and withdrawing money.
Now, let's make our class use a primary constructor:
public class BankAccount(string accountNumber, decimal balance)
{
public decimal Balance { get; set; } = balance;
public void Deposit(decimal amount)
{
Balance += amount;
Console.WriteLine($"Deposited {amount:C} to {accountNumber}. New balance: {Balance:C}");
}
public void Withdraw(decimal amount)
{
if (amount <= Balance)
{
Balance -= amount;
Console.WriteLine($"Withdrawn {amount:C} from {accountNumber}. New balance: {Balance:C}");
}
else
{
Console.WriteLine($"Insufficient funds on {accountNumber}.");
}
}
}
Just as with record types, the constructor parameters move to the very first line, where we declare our class. The parameters are in scope everywhere inside the class, so we assign the Balance property directly from balance, and we replace all references to _accountNumber with accountNumber. The rest of our class remains unchanged, and we've reduced our code by eight lines.
If we need additional constructors, they must call the primary one using this():
public BankAccount(string accountNumber) : this(accountNumber, 0)
{
}
Primary Constructors for Structs
Structs get the exact same syntax:
public readonly struct Coordinates(double latitude, double longitude)
{
public double Latitude => latitude;
public double Longitude => longitude;
public override string ToString() => $"{latitude}, {longitude}";
}
Here, we have a Coordinates struct that we can use to store where each cat in our shelter was found. Since structs with primary constructors don't get properties either, we expose the values through two read-only properties.
Notice that our struct is readonly. In a readonly struct, the compiler won't let us assign to the captured parameters, which is exactly what we want from a small value type. In a regular struct or class, as we'll see in a moment, that's not the case.
What Happens Behind the Scenes
It's essential to remember that no properties are generated for the parameters of classes and structs. This is the biggest difference compared to records.
Instead, the compiler decides what to do with each parameter based on how we use it:
- If a parameter is only used to initialize fields or properties, like
balancein ourBankAccountclass, nothing extra is generated. It's just a constructor parameter. - If a parameter is used inside a method or property, like
accountNumber, the compiler captures it into a hidden private field, so it's available for the whole lifetime of the object.
These hidden fields have unspeakable names, so we can't access them directly. We also can't access a parameter through this, as in this.accountNumber.
This is also why we name primary constructor parameters in classes and structs in camelCase, like any other parameter, while for records, we use PascalCase, as they become public properties.
Finally, primary constructors don't change anything when it comes to equality. Classes still have reference-based equality, and structs still compare their values.
Captured Parameters Are Not Readonly
This is the pitfall that catches most people. Let's say we have a service that uses a repository:
public class CatService(ICatRepository repository) : ICatService
{
public Task<Cat?> GetByIdAsync(int id, CancellationToken cancellationToken)
{
return repository.GetByIdAsync(id, cancellationToken);
}
public void Reset()
{
repository = null!;
}
}
The Reset() method compiles without any warnings. Captured parameters behave like regular, mutable fields, so anything inside our class can reassign them. With the old-fashioned constructor and a private readonly field, the compiler would've stopped us.
If we want that guarantee back, we can assign the parameter to a readonly field ourselves:
public class CatService(ICatRepository repository) : ICatService
{
private readonly ICatRepository _repository = repository;
public Task<Cat?> GetByIdAsync(int id, CancellationToken cancellationToken)
{
return _repository.GetByIdAsync(id, cancellationToken);
}
}
Since repository is now only used to initialize our field, it isn't captured, and we have a single, readonly source of truth.
But be careful not to mix the two approaches. If we initialize _repository and also use repository directly somewhere in our class, the compiler captures the parameter as well, and we end up with two copies of the same value. The compiler warns us about this with CS9124: the parameter is captured into the state of the enclosing type, and its value is also used to initialize a field. If we then change one of them, the other one won't know about it.
Primary Constructors and Dependency Injection
Despite the pitfall above, dependency injection is where primary constructors really shine. Most of our services only take their dependencies and use them, so there's a lot of boilerplate to remove:
public class CatService(
ICatRepository repository,
ILogger<CatService> logger) : ICatService
{
public async Task<Cat?> GetByIdAsync(int id, CancellationToken cancellationToken)
{
var cat = await repository.GetByIdAsync(id, cancellationToken);
if (cat is null)
{
logger.LogWarning("Cat with ID {CatId} was not found", id);
}
return cat;
}
}
No fields, no constructor body, and no assignments. The DI container doesn't care whether we use a primary constructor or a regular one, so this works out of the box.
Primary constructors also make passing values to a base class very clean. We can see this with the DbContext I use in many of my articles:
public class CatDbContext(DbContextOptions<CatDbContext> options)
: DbContext(options)
{
public virtual DbSet<Cat> Cats { get; set; }
}
We pass the options parameter straight to the base DbContext constructor.
In my own projects, I use primary constructors for services like these and accept that the parameters are mutable. I don't reassign dependencies anyway, and the code is much easier to read.
Primary Constructors and Validation Logic
Let's go back to our BankAccount class and imagine we must make sure that the balance is never negative and the account number is 10 characters long:
public class BankAccount(string accountNumber, decimal balance)
{
private readonly string _accountNumber = VerifyAccountNumber(accountNumber);
public decimal Balance
{
get => balance;
set
{
ArgumentOutOfRangeException.ThrowIfNegative(value);
balance = value;
}
}
public void Deposit(decimal amount)
{
Balance += amount;
Console.WriteLine($"Deposited {amount:C} to {_accountNumber}. New balance: {Balance:C}");
}
private static string VerifyAccountNumber(string accountNumber)
{
if (accountNumber.Length != 10)
{
throw new ArgumentException("Account number is invalid", nameof(accountNumber));
}
return accountNumber;
}
}
We expand the setter of the Balance property and validate the new value with the ThrowIfNegative() method. Note that the setter assigns to the captured balance parameter, which works precisely because captured parameters are mutable. For the account number, we need a field again, so I've opted for a static validation method that we call from the field initializer.
There's one more catch here: the setter only runs when we set Balance. A negative balance passed to the constructor is never validated. Primary constructors have no body, so there's no single place to validate all of our parameters. At this point, our code has become more complicated than if we used an old-fashioned constructor, and that's usually a sign that a regular constructor is the better choice.
Code Formatting and Primary Constructors
We've all gotten used to formatting our code in a certain way. Let's look at the following example:
public class BankAccountService(List<BankAccount> bankAccounts) : IBankAccountService
{
public List<BankAccount> BankAccounts { get; set; } = bankAccounts;
}
We have a BankAccountService that implements the IBankAccountService interface and uses a primary constructor. With one parameter, a single line is fine, but what happens when we have more? Do we split them like this:
public class BankAccountService(
List<BankAccount> bankAccounts,
Accountant accountManager,
Accountant accountSupervisor) : IBankAccountService
{
public List<BankAccount> BankAccounts { get; set; } = bankAccounts;
public Accountant AccountManager { get; set; } = accountManager;
public Accountant AccountSupervisor { get; set; } = accountSupervisor;
}
Or do we move the interface to a new line as well?
public class BankAccountService(
List<BankAccount> bankAccounts,
Accountant accountManager,
Accountant accountSupervisor)
: IBankAccountService
{
public List<BankAccount> BankAccounts { get; set; } = bankAccounts;
public Accountant AccountManager { get; set; } = accountManager;
public Accountant AccountSupervisor { get; set; } = accountSupervisor;
}
This might seem like a trivial problem, but we still need a convention, at least on a team level, for how to format our code. If it was up to me, I'd go with the first option, and I do so in most of my projects. For base classes with arguments, like our CatDbContext, I move the base class to a new line, as it keeps the constructor call readable.
Conclusion
Primary constructors bring the conciseness of records to classes and structs, and for services that just take and use their dependencies, they remove a lot of boilerplate.
However, they're not a drop-in replacement for every constructor. Parameters don't become properties, captured parameters are mutable, and there's no constructor body for validation. If you keep these differences in mind, primary constructors are a great tool to have in your C# toolbox.
Frequently Asked Questions
Do primary constructors in classes create properties?
No. Only records get public properties. In classes and structs, parameters are either used for initialization or captured into hidden private fields.
Can I make primary constructor parameters readonly?
Not directly. Either assign the parameter to a private readonly field, or use a readonly struct, where captured parameters can't be reassigned.
What does warning CS9124 mean?
It means a parameter is captured and also used to initialize a field or property, so there are two copies of the same value. Use either the parameter or the field, not both.
Can I have more than one constructor in a class with a primary constructor?
Yes, but every additional constructor must call the primary constructor using this().
Do primary constructors work with dependency injection?
Yes. The DI container treats them like any other constructor.
Can interfaces have primary constructors?
No. Primary constructors are available for classes, structs, and records only.