ZetCode

C# primary constructors

last modified November 15, 2026

This article shows how to use primary constructors in C# classes and structs. We cover parameter capture, additional constructors, inheritance, validation, the double storage pitfall, and the differences from records.

A primary constructor declares constructor parameters directly after the type name: class Person(string name, int age). Primary constructors were available for records since C# 9; C# 12 extended them to all classes and structs. The parameters are in scope in the whole body of the type. They can initialize fields and properties, and they can be used directly in methods, properties, and other members.

Unlike in records, the parameters of a primary constructor in a class or struct do not become public properties. They are plain parameters. If a member other than an initializer uses a parameter, the compiler stores the parameter in a hidden private field; this is called capturing.

A simple primary constructor

The most common use of primary constructor parameters is to initialize properties.

Program.cs
var p = new Person("John Doe", "gardener");
Console.WriteLine(p.Name);
Console.WriteLine(p.Occupation);
Console.WriteLine(p);

class Person(string name, string occupation)
{
    public string Name { get; } = name;
    public string Occupation { get; } = occupation;

    public override string ToString() => $"{Name} is a {Occupation}";
}

The Person class has a primary constructor with two parameters.

class Person(string name, string occupation)

The parameter list follows the class name. This replaces a separate constructor that would assign the parameters to the properties.

public string Name { get; } = name;
public string Occupation { get; } = occupation;

The parameters initialize two read-only auto-implemented properties. The initializers run as part of the primary constructor.

public override string ToString() => $"{Name} is a {Occupation}";

The ToString method uses the properties, not the parameters. The parameters are therefore used only in initializers and the compiler does not need to store them anywhere.

$ dotnet run
John Doe
gardener
John Doe is a gardener

Captured parameters

When a method or property uses a primary constructor parameter, the compiler captures it in a private field. The captured parameter is mutable.

Program.cs
var c = new Counter(5);

c.Increment();
c.Increment();
c.Increment();

Console.WriteLine(c.Value);

class Counter(int start)
{
    public void Increment() => start++;

    public int Value => start;
}

The Counter class works with its start parameter directly, without declaring a field.

public void Increment() => start++;

The method modifies the parameter. Since the parameter is captured, the change persists between calls. Primary constructor parameters cannot be declared readonly; if we need an immutable value, we assign the parameter to a readonly field or a get-only property.

public int Value => start;

The Value property reads the current state of the captured parameter. The parameter is not accessible from outside the class.

$ dotnet run
8

Primary constructors in structs

Structs can have primary constructors too. A struct always keeps its parameterless constructor, which sets all fields to their default values.

Program.cs
var p1 = new Point(3, 4);
var p2 = new Point();

Console.WriteLine(p1);
Console.WriteLine(p1.Distance());
Console.WriteLine(p2);

readonly struct Point(double x, double y)
{
    public double X { get; } = x;
    public double Y { get; } = y;

    public double Distance() => Math.Sqrt(X * X + Y * Y);

    public override string ToString() => $"({X}, {Y})";
}

The Point struct takes the coordinates in its primary constructor.

readonly struct Point(double x, double y)

The struct is readonly. A readonly struct cannot modify captured parameters, so the example uses them only to initialize the properties.

var p2 = new Point();

The parameterless constructor bypasses the primary constructor. The properties of p2 are zero.

$ dotnet run
(3, 4)
5
(0, 0)

Additional constructors

A type with a primary constructor may declare other constructors, but each of them must call the primary constructor, directly or indirectly, with the this(...) initializer.

Program.cs
var r1 = new Rectangle(4, 5);
var r2 = new Rectangle(3);
var r3 = new Rectangle();

Console.WriteLine(r1);
Console.WriteLine(r2);
Console.WriteLine(r3);

class Rectangle(int width, int height)
{
    public Rectangle(int side) : this(side, side) { }

    public Rectangle() : this(1) { }

    public int Area => width * height;

    public override string ToString() =>
        $"{width}x{height} rectangle, area {Area}";
}

The Rectangle class has three ways of construction.

public Rectangle(int side) : this(side, side) { }

The constructor for a square passes the side twice to the primary constructor.

public Rectangle() : this(1) { }

The parameterless constructor calls the square constructor, which in turn calls the primary constructor. Leaving out the this initializer is a compile-time error.

$ dotnet run
4x5 rectangle, area 20
3x3 rectangle, area 9
1x1 rectangle, area 1

Inheritance

A derived class can pass its primary constructor parameters to the constructor of the base class right in the base class list.

Program.cs
Animal[] animals = [new Dog("Rex", 4), new Bird("Tweety", true)];

foreach (var animal in animals)
{
    Console.WriteLine(animal.Describe());
}

abstract class Animal(string name)
{
    public string Name => name;

    public abstract string Describe();
}

class Dog(string name, int legs) : Animal(name)
{
    public override string Describe() => $"{Name} is a dog with {legs} legs";
}

class Bird(string name, bool canFly) : Animal(name)
{
    public override string Describe() =>
        $"{Name} is a bird that {(canFly ? "can" : "cannot")} fly";
}

The Animal base class has a primary constructor with a name parameter.

abstract class Animal(string name)
{
    public string Name => name;

The Name property captures the name parameter.

class Dog(string name, int legs) : Animal(name)

The Dog class forwards its name parameter to the base class. Inside Dog, the example uses the inherited Name property rather than the name parameter; using both would store the same value twice, once in each class, and the compiler would warn about it.

$ dotnet run
Rex is a dog with 4 legs
Tweety is a bird that can fly

Validation

A primary constructor has no body. Validation goes into the initializers, where throw expressions are handy.

Program.cs
var u1 = new User("johndoe", 34);
Console.WriteLine($"{u1.Login} {u1.Age}");

try
{
    var u2 = new User(" ", 20);
}
catch (ArgumentException e)
{
    Console.WriteLine(e.Message);
}

try
{
    var u3 = new User("roger", -5);
}
catch (ArgumentOutOfRangeException e)
{
    Console.WriteLine(e.Message);
}

class User(string login, int age)
{
    public string Login { get; } = string.IsNullOrWhiteSpace(login)
        ? throw new ArgumentException("login must not be empty", nameof(login))
        : login;

    public int Age { get; } = age >= 0 ? age
        : throw new ArgumentOutOfRangeException(nameof(age), "age must not be negative");
}

The User class rejects an empty login and a negative age.

public string Login { get; } = string.IsNullOrWhiteSpace(login)
    ? throw new ArgumentException("login must not be empty", nameof(login))
    : login;

The conditional operator returns the parameter if it is valid and throws an exception otherwise. The initializer runs when the object is created.

$ dotnet run
johndoe 34
login must not be empty (Parameter 'login')
age must not be negative (Parameter 'age')

The double storage pitfall

If a parameter both initializes a property and is used in a member, the class ends up with two independent copies of the value. They can get out of sync.

Program.cs
var acc = new Account("Peter", 100);

acc.Deposit(50);

Console.WriteLine(acc.Owner);
Console.WriteLine(acc.Balance);

class Account(string owner, decimal balance)
{
    public string Owner { get; } = owner;
    public decimal Balance { get; } = balance;

    public void Deposit(decimal amount) => balance += amount;
}

The Account class initializes the Balance property from the balance parameter, but the Deposit method modifies the parameter.

public void Deposit(decimal amount) => balance += amount;

The method changes the captured copy, while the Balance property still holds the initial value. After the deposit, the balance remains 100. The compiler detects the situation and issues the CS9124 warning. The fix is to use only one storage: make Balance a property with a private setter and update the property in Deposit.

$ dotnet build
Program.cs(11,39): warning CS9124: Parameter 'decimal balance' is captured into the state of the enclosing type and its value is also used to initialize a field, property, or event.
$ dotnet run
Peter
100

Primary constructors and records

Records use the same syntax, but the compiler generates much more for them.

Program.cs
var c1 = new CarClass("Toyota", 2020);
var c2 = new CarClass("Toyota", 2020);

var r1 = new CarRecord("Toyota", 2020);
var r2 = new CarRecord("Toyota", 2020);

Console.WriteLine(c1);
Console.WriteLine(r1);

Console.WriteLine(c1 == c2);
Console.WriteLine(r1 == r2);

Console.WriteLine(r1.Make);

class CarClass(string make, int year)
{
    public string Info() => $"{make} {year}";
}

record CarRecord(string Make, int Year);

We compare a class and a record that have the same primary constructor.

record CarRecord(string Make, int Year);

In a record, the parameters become public init-only properties. The compiler also generates value-based equality, a ToString method that prints the properties, a deconstructor, and support for the with expression. The class gets none of these: its ToString prints just the type name and == compares references. Primary constructors in classes are a shortcut for writing constructors; records are a different kind of type.

$ dotnet run
CarClass
CarRecord { Make = Toyota, Year = 2020 }
False
True
Toyota

Dependency injection

Primary constructors are well suited for classes that receive their dependencies through the constructor. The dependencies are captured and used in the methods without explicit fields.

Program.cs
var store = new MemoryStore();
var service = new OrderService(store, new ConsoleLogger());

service.Place("book");
service.Place("pen");

Console.WriteLine(string.Join(", ", store.Items));

interface IStore { void Save(string item); }
interface ILogger { void Log(string message); }

class MemoryStore : IStore
{
    public List<string> Items { get; } = [];
    public void Save(string item) => Items.Add(item);
}

class ConsoleLogger : ILogger
{
    public void Log(string message) => Console.WriteLine($"log: {message}");
}

class OrderService(IStore store, ILogger logger)
{
    public void Place(string item)
    {
        store.Save(item);
        logger.Log($"order for {item} placed");
    }
}

The OrderService depends on a store and a logger.

class OrderService(IStore store, ILogger logger)
{
    public void Place(string item)
    {
        store.Save(item);
        logger.Log($"order for {item} placed");
    }
}

Without a primary constructor, the class would need two private fields and a constructor that assigns them. The same pattern is used with the built-in dependency injection container of ASP.NET Core.

$ dotnet run
log: order for book placed
log: order for pen placed
book, pen

Source

Primary constructors

Tutorial: Explore primary constructors

In this article we have worked with primary constructors in C#. See also the constructor, record, struct, and inheritance tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.