Primary constructors
suggest changeA primary constructor is a parameter list written right after the type name:
class OrderService(IOrderStore store, IClock clock)
{
public void Place(string item) => store.Add($"{clock.Now:yyyy-MM-dd HH:mm} {item}");
}
This replaces the usual boilerplate: a constructor, private fields, and the assignments that copy each parameter into a field. The parameters store and clock can be used anywhere in the body of the class.
Versions:
- C# 9 (.NET 5): primary constructors for
recordtypes only (see Records) - C# 12 (.NET 8): primary constructors for any
classandstruct
They look the same in records and in classes, but they behave very differently. A record turns each parameter into a public property. A class or struct generates nothing public: the parameters are only in scope inside the type. The last section compares the two.
The examples are .NET 10 / C# 14 file-based programs: save the code as app.cs and run it with dotnet run app.cs. All output comes from real runs.
The basics
var c = new Counter("clicks", 10);
c.Increment();
c.Increment();
Console.WriteLine(c);
class Counter(string name, int start)
{
private int _value = start;
public void Increment() => _value++;
public override string ToString() => $"{name}: {_value}";
}
clicks: 12
What happened:
new Counter("clicks", 10)calls the primary constructor. It's the only constructor the class has.startis used in a field initializer to set_value.nameis used in a method,ToString. To make that work, the compiler storesnamein a hidden field.
The parameters are not members. You can't write this.name or c.name:
var p = new Pt(1, 2);
Console.WriteLine(p.x);
class Pt(int x, int y)
{
public int Sum => x + y;
}
error CS1061: 'Pt' does not contain a definition for 'x' and no accessible extension method 'x' accepting a first argument of type 'Pt' could be found (are you missing a using directive or an assembly reference?)
If callers need the value, expose it with a property.
Initializing properties and fields
The simplest use is to copy parameters into properties or fields. Initializers can use the parameters in any expression:
var p = new Person("Ada", "Lovelace");
Console.WriteLine(p.FullName);
Console.WriteLine(p.Initials);
class Person(string first, string last)
{
public string First { get; } = first;
public string Last { get; } = last;
public string FullName => $"{First} {Last}";
public string Initials { get; } = $"{first[0]}{last[0]}";
}
Ada Lovelace
AL
FullName uses the properties, not the parameters. That matters, as you'll see below.
Validation
A primary constructor has no body, so there's no place for if (...) throw statements. Put the check into the initializer with a throw expression:
var u = new User(" ada ", 36);
Console.WriteLine($"[{u.Name}] {u.Age}");
try { new User(" ", 20); }
catch (ArgumentException e) { Console.WriteLine(e.Message); }
try { new User("Bob", -1); }
catch (ArgumentException e) { Console.WriteLine(e.Message); }
class User(string name, int age)
{
public string Name { get; } = string.IsNullOrWhiteSpace(name)
? throw new ArgumentException("Name is required.", nameof(name))
: name.Trim();
public int Age { get; } = age >= 0
? age
: throw new ArgumentOutOfRangeException(nameof(age), age, "Age can't be negative.");
}
[ada] 36
Name is required. (Parameter 'name')
Age can't be negative. (Parameter 'age')
Actual value was -1.
Initializers run in the order they're written, before any other constructor body. If validation gets longer than a line or two, write a normal constructor instead. Primary constructors are meant for simple cases.
Captured parameters
A parameter used only in initializers is just a constructor argument. A parameter used in a method, property or lambda is captured: the compiler adds a private field to hold it. Reflection shows the difference:
using System.Reflection;
const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
Console.WriteLine("OnlyInitializers:");
foreach (var f in typeof(OnlyInitializers).GetFields(flags))
Console.WriteLine($" {f.FieldType.Name} {f.Name}, readonly: {f.IsInitOnly}");
Console.WriteLine("Captured:");
foreach (var f in typeof(Captured).GetFields(flags))
Console.WriteLine($" {f.FieldType.Name} {f.Name}, readonly: {f.IsInitOnly}");
class OnlyInitializers(int x)
{
public int X { get; } = x;
}
class Captured(int x)
{
public int Twice() => x * 2;
}
OnlyInitializers:
Int32 <X>k__BackingField, readonly: True
Captured:
Int32 <x>P, readonly: False
OnlyInitializers has just the backing field of property X; the parameter x isn't stored. Captured gets a field named <x>P, which you can't refer to from C#. Note readonly: False: the captured field is mutable.
Parameters are mutable
A captured parameter behaves like a mutable field. You can assign to it, and nothing warns you:
var acc = new Account(100m);
acc.Withdraw(30m);
acc.Withdraw(30m);
Console.WriteLine(acc.Balance);
class Account(decimal balance)
{
public decimal Balance => balance;
public void Withdraw(decimal amount)
{
balance -= amount; // compiles: the parameter is a mutable variable
}
}
40
Sometimes that's what you want. More often it's a bug, like overwriting a dependency by accident:
var w = new Worker(Console.Out);
w.Run();
class Worker(TextWriter output)
{
public void Run()
{
output.WriteLine("working");
output = TextWriter.Null; // oops: no error, no warning
output.WriteLine("lost");
}
}
working
There is no readonly modifier for primary constructor parameters. To get a read-only value, copy the parameter into a readonly field.
Making a parameter read-only
You can give the field the same name as the parameter. Inside the field initializer, greeting means the parameter. Everywhere else in the class, it means the field:
var g = new Greeter("Hello");
Console.WriteLine(g.Greet("Ada"));
class Greeter(string greeting)
{
private readonly string greeting = greeting;
public string Greet(string name) => $"{greeting}, {name}!";
}
Hello, Ada!
Now the parameter isn't captured (it's only used in an initializer), and assigning to greeting in a method fails:
error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer)
Many teams use _greeting for the field name instead. Both work; with a different name, the parameter stays in scope in methods, so you can accidentally use it there and capture it.
In a readonly struct, captured parameters are read-only automatically:
readonly struct Vec(double x, double y)
{
public void Scale(double k) { x *= k; y *= k; }
}
error CS9114: A primary constructor parameter of a readonly type cannot be assigned to (except in init-only setter of the type or a variable initializer)
Double storage
A classic mistake is to use a parameter both to initialize a property and in a method. The value is then stored twice, and the two copies can drift apart:
var item = new Item("Pen");
item.Rename("Pencil");
Console.WriteLine(item.Name);
Console.WriteLine(item.Describe());
class Item(string name)
{
public string Name { get; private set; } = name;
public void Rename(string newName) => Name = newName;
public string Describe() => $"Item {name}";
}
warning CS9124: Parameter 'string name' is captured into the state of the enclosing type and its value is also used to initialize a field, property, or event.
Pencil
Item Pen
Describe reads the captured parameter, which still says Pen. The compiler warns about this (CS9124). The fix is to use the property everywhere: $"Item {Name}". Treat that warning as an error.
Other constructors must call the primary constructor
You can add more constructors, but each one must chain to the primary constructor with : this(...). That guarantees the parameters are always set:
var a = new Point(3, 4);
var b = new Point();
var c = new Point(7);
Console.WriteLine($"{a} {b} {c}");
class Point(int x, int y)
{
public Point() : this(0, 0) { }
public Point(int both) : this(both, both) { }
public int X { get; } = x;
public int Y { get; } = y;
public override string ToString() => $"({X}, {Y})";
}
(3, 4) (0, 0) (7, 7)
Leave out the : this(...) and you get:
error CS8862: A constructor declared in a type with parameter list must have 'this' constructor initializer.
See Calling a constructor from another constructor for how chaining works with ordinary constructors.
Calling the base class constructor
Pass arguments to the base class right in the class header:
var d = new FileLogger("app.log", LogLevel.Warning);
d.Log(LogLevel.Info, "starting");
d.Log(LogLevel.Error, "disk full");
enum LogLevel { Info, Warning, Error }
abstract class Logger(LogLevel minLevel)
{
public void Log(LogLevel level, string message)
{
if (level >= minLevel) Write($"[{level}] {message}");
}
protected abstract void Write(string line);
}
class FileLogger(string path, LogLevel minLevel) : Logger(minLevel)
{
protected override void Write(string line) => Console.WriteLine($"{path}: {line}");
}
app.log: [Error] disk full
minLevel is passed through to Logger and isn't used anywhere else in FileLogger, so FileLogger doesn't store it. If the derived class also used it in a method, both classes would keep their own copy, the same double-storage problem as above:
var d = new Derived("x");
d.Rename("y");
Console.WriteLine(d.Show());
class Base(string name)
{
public string Name { get; set; } = name;
}
class Derived(string name) : Base(name)
{
public void Rename(string n) => Name = n;
public string Show() => $"Name={Name}, name={name}";
}
warning CS9107: Parameter 'string name' is captured into the state of the enclosing type and its value is also passed to the base constructor. The value might be captured by the base class as well.
Name=y, name=x
In Derived, use the inherited Name property instead of the parameter.
Structs
Structs get primary constructors too:
var a = new Vec(3, 4);
var b = new Vec();
var c = default(Vec);
Console.WriteLine($"{a.Length} {b.Length} {c.Length}");
readonly struct Vec(double x, double y)
{
public double X => x;
public double Y => y;
public double Length => Math.Sqrt(x * x + y * y);
}
5 0 0
A struct always has a parameterless constructor too, and new Vec() and default(Vec) skip the primary constructor and leave every field zeroed. Your code must handle that state; you can't stop callers from creating it.
Dependency injection
Services that receive their dependencies through the constructor are the main reason primary constructors were added to classes. Before C# 12, each dependency was written three times: field, parameter, assignment. Now it's written once:
#:package Microsoft.Extensions.DependencyInjection@10.0.13
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddSingleton<IClock, FixedClock>();
services.AddSingleton<IOrderStore, MemoryOrderStore>();
services.AddTransient<OrderService>();
using var provider = services.BuildServiceProvider();
var orders = provider.GetRequiredService<OrderService>();
orders.Place("keyboard");
orders.Place("mouse");
foreach (var line in provider.GetRequiredService<IOrderStore>().All())
Console.WriteLine(line);
interface IClock { DateTime Now { get; } }
interface IOrderStore { void Add(string order); IEnumerable<string> All(); }
class FixedClock : IClock
{
public DateTime Now => new(2026, 10, 18, 9, 30, 0);
}
class MemoryOrderStore : IOrderStore
{
private readonly List<string> _orders = [];
public void Add(string order) => _orders.Add(order);
public IEnumerable<string> All() => _orders;
}
class OrderService(IOrderStore store, IClock clock)
{
public void Place(string item) => store.Add($"{clock.Now:yyyy-MM-dd HH:mm} {item}");
}
2026-10-18 09:30 keyboard
2026-10-18 09:30 mouse
The container sees OrderService's single constructor, resolves IOrderStore and IClock, and calls it. The same works for ASP.NET Core controllers, minimal API services, hosted services and anything else the container builds. The Configuration files article shows a service that takes IOptions<T> this way.
For services the mutability of captured parameters rarely bites, but if you want the compiler to stop accidental reassignment, use the private readonly IClock clock = clock; pattern from above.
Other rules
-
Only one declaration of a
partialtype may have the parameter list:error CS8863: Only a single partial type declaration may have a parameter list -
A parameter that is never used gets warning CS9113 (
Parameter 'x' is unread.). -
Parameters can have default values and modifiers like
params:class Query(string table, int limit = 100). -
Parameters aren't in scope in static members, since static members have no instance to read them from.
-
A class with a primary constructor has no implicit parameterless constructor. If you need one (for a serializer, say), add
public Point() : this(0, 0) { }.
Primary constructors in classes vs records
The same syntax on a record generates a lot more:
var p = new Pt(1, 2);
var r = new RPt(1, 2);
Console.WriteLine(p);
Console.WriteLine(r);
Console.WriteLine(r.X);
Console.WriteLine(p.Equals(new Pt(1, 2)));
Console.WriteLine(r.Equals(new RPt(1, 2)));
class Pt(int x, int y)
{
public int Sum => x + y;
}
record RPt(int X, int Y);
Pt
RPt { X = 1, Y = 2 }
1
False
True
class C(int x) / struct S(int x) |
record R(int X) |
|
|---|---|---|
| Public property per parameter | no | yes (init-only; get; set; for a non-readonly record struct) |
| Parameter stored | only if captured, in a hidden mutable field | always, in the property's backing field |
Value equality, ToString, with, Deconstruct |
no | yes |
| Naming convention | camelCase, like any parameter |
PascalCase, because they become properties |
| Typical use | services, classes with behavior, simple value holders | data: DTOs, messages, results |
Pick a record when the parameters are the data. Pick a class with a primary constructor when the parameters are dependencies or settings the object uses to do its job. The Records article covers record primary constructors in detail.
When to use a primary constructor
Good fits:
- Services that take dependencies and just use them.
- Small classes where each parameter becomes a property, with at most a one-line check.
- Derived classes that only pass arguments to the base class.
Prefer an ordinary constructor when:
- Construction has several steps, logging, or validation that doesn't fit in an initializer.
- You need parameters stored in
readonlyfields and don't want to repeat every name in a field declaration anyway. - The type has several unrelated constructors that don't share one main set of parameters.
See Constructors and Finalizers for ordinary constructors.