Primary Constructors in C#: Examples, DI and Inheritance

Say you’re writing checkout code for Ridgeline Outfitters, a gear shop in Boise, Idaho. Every class opens with the same chore: declare private fields, write a constructor, copy each argument across.

A C# primary constructor cuts that to one line. Put the parameters right after the class name, like class Order(string customer, decimal subtotal), and use them anywhere in the class body.

I rebuilt the shop’s order classes on .NET 10, including a DI service, a derived class, validation and the double-storage warnings.

The Sample Ridgeline Orders for the Primary Constructor Demos

Each demo is a .NET 10 file-based app (C# 14) that you start with dotnet run File.cs; file-based apps with dotnet run explains the setup. The running sample:

  • Jenna Morales, $89.99, shipping in Idaho (6% sales tax)
  • Tyler Brooks, $42.50, shipping to Oregon (no sales tax)
  • A gift order to test inheritance
  • A blank name and a -$5 subtotal to test validation

What Is a Primary Constructor in C#?

A primary constructor puts the constructor’s parameters in the type declaration. Classes and structs got it in C# 12 (.NET 8); records have had it since C# 9, and it works the same in C# 14.

Here’s Jenna’s order with no fields and no constructor body:

#:property PublishAot=false
var order = new Order("Jenna Morales", 89.99m);
Console.WriteLine(order.Describe());
Console.WriteLine($"Total with Idaho tax: ${order.Total}");

public class Order(string customer, decimal subtotal)
{
    public decimal Total => Math.Round(subtotal * 1.06m, 2);

    public string Describe() => $"{customer} ordered ${subtotal}";
}

Output:

Jenna Morales ordered $89.99
Total with Idaho tax: $95.39
C# primary constructor example in VS Code: class Order(string customer, decimal subtotal) uses both parameters in a property and a method, and dotnet run prints Jenna Morales ordered $89.99 and a total of $95.39
One line replaces two private fields and a constructor

It prints the order and an Idaho total of $95.39.

How does this code work?

The compiler turns (string customer, decimal subtotal) into a public constructor. Both parameters are in scope in the whole class, so Total and Describe() read them like local variables.

Because methods use them, the compiler stores each one in a hidden private field. If only an initializer read them, no field would exist at all.

Primary Constructor vs Record: Parameters Aren’t Properties

On a class or struct, primary constructor parameters are just parameters. Only a record turns them into public properties. Same order data, as a class and as a record:

#:property PublishAot=false
var order = new Order("Jenna Morales", 89.99m);
var record = new OrderRecord("Jenna Morales", 89.99m);

Console.WriteLine(order);
Console.WriteLine(record);
Console.WriteLine($"record.Customer = {record.Customer}");
Console.WriteLine(order == new Order("Jenna Morales", 89.99m));
Console.WriteLine(record == new OrderRecord("Jenna Morales", 89.99m));

public class Order(string customer, decimal subtotal)
{
    public string Describe() => $"{customer} ordered ${subtotal}";
}

public record OrderRecord(string Customer, decimal Subtotal);

Output:

Order
OrderRecord { Customer = Jenna Morales, Subtotal = 89.99 }
record.Customer = Jenna Morales
False
True
C# primary constructor vs record in VS Code: printing the class shows only the type name Order while the record prints Customer and Subtotal, and only the record compares equal by value
The record gets properties, ToString and value equality; the class gets none of them

The class prints just Order and two identical orders aren’t equal. The record prints its values and compares by value.

How does this work?

A record synthesizes properties, ToString and equality from its parameters. A class synthesizes nothing public, so order.customer and even this.customer fail with CS1061 (I tried both).

Use a record for data you compare and print, and a class for behavior; the record vs class vs struct comparison goes deeper.

Method 1: Use the Captured Primary Constructor Parameter Directly

The simplest way is to read the parameter in your methods, as Order did. The catch: a captured parameter is mutable. Same shop, now Tyler’s cart:

#:property PublishAot=false
var cart = new Cart("Tyler Brooks", 42.50m);
cart.Add(19.99m);
cart.Add(8.25m);
Console.WriteLine(cart.Summary());

public class Cart(string customer, decimal subtotal)
{
    public void Add(decimal price) => subtotal += price;

    public void Reset() => customer = "";   // compiles

    public string Summary() => $"{customer}: ${subtotal}";
}

Output:

Tyler Brooks: $70.74
C# primary constructor parameter captured and mutable in VS Code: the Cart class adds to the subtotal parameter with += and the output shows Tyler Brooks: $70.74
The subtotal parameter changed from $42.50 to $70.74

Tyler’s subtotal went from $42.50 to $70.74 after two Add calls.

How does this code work?

subtotal += price writes to the hidden field. Nothing makes it readonly, which is why Reset can blank the customer name and still compile.

Method 2: Assign the Primary Constructor Parameter to a Property or readonly Field

When a value must stay fixed, copy the parameter into a get-only property or a readonly field, then use only the member. Same Jenna Morales order:

#:property PublishAot=false
var order = new Order("Jenna Morales", 89.99m);
Console.WriteLine($"{order.Customer} | ${order.Subtotal} | {order.Region}");

public class Order(string customer, decimal subtotal, string state = "ID")
{
    public string Customer { get; } = customer;
    public decimal Subtotal { get; } = subtotal;

    private readonly string _state = state;
    public string Region => _state == "ID" ? "Idaho" : _state;
}

Output:

Jenna Morales | $89.99 | Idaho

How does this work?

Initializers run as part of the primary constructor. No method reads the parameters, so nothing is captured and each value lives in one place, the kind of control encapsulation in C# is about.

Important: once you copy a parameter, stop using the parameter in methods, or you get two copies and warning CS9124 (shown below).

How Do You Validate Primary Constructor Parameters?

There’s no constructor body, so validation goes in the initializers. ArgumentException.ThrowIfNullOrWhiteSpace and ArgumentNullException.ThrowIfNull return void, so I wrap the first one in a helper that returns the value.

Same order class, fed a blank name and a -$5 subtotal:

#:property PublishAot=false
using System.Runtime.CompilerServices;

var order = new Order("Jenna Morales", 89.99m);
Console.WriteLine($"Created order for {order.Customer}");

try { _ = new Order("   ", 42.50m); }
catch (ArgumentException ex) { Console.WriteLine(ex.Message); }
try { _ = new Order("Tyler Brooks", -5m); }
catch (ArgumentException ex) { Console.WriteLine(ex.Message); }

public class Order(string customer, decimal subtotal)
{
    public string Customer { get; } = NotBlank(customer);
    public decimal Subtotal { get; } = subtotal >= 0 ? subtotal
        : throw new ArgumentOutOfRangeException(nameof(subtotal), "Subtotal can't be negative.");

    static string NotBlank(string value, [CallerArgumentExpression(nameof(value))] string? name = null)
    { ArgumentException.ThrowIfNullOrWhiteSpace(value, name); return value; }
}

Output:

Created order for Jenna Morales
The value cannot be an empty string or composed entirely of whitespace. (Parameter 'customer')
Subtotal can't be negative. (Parameter 'subtotal')
C# primary constructor validation in VS Code: property initializers call ArgumentException.ThrowIfNullOrWhiteSpace and throw ArgumentOutOfRangeException, and the output shows both exception messages
Bad arguments throw while the object is being created

How does this code work?

[CallerArgumentExpression] fills in the name customer, and the ?: with throw handles the subtotal inline. For a null check, customer ?? throw new ArgumentNullException(nameof(customer)) needs no helper.

Add nullable reference types for compile-time warnings and a try-catch block where you create the object.

Primary Constructor Dependency Injection in a Service

This is where primary constructors pay off most. A service lists its dependencies once, and ASP.NET Core dependency injection calls that constructor for you.

Same checkout, now an OrderService resolved from the Generic Host (Microsoft.Extensions.Hosting 10.0.14):

#:package Microsoft.Extensions.Hosting@10.0.14
#:property PublishAot=false
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddSingleton<ITaxRates, IdahoTaxRates>();
builder.Services.AddTransient<OrderService>();
using var host = builder.Build();

var checkout = host.Services.GetRequiredService<OrderService>();
Console.WriteLine(checkout.Checkout("Jenna Morales", 89.99m, "ID"));
Console.WriteLine(checkout.Checkout("Tyler Brooks", 42.50m, "OR"));

public class OrderService(ITaxRates taxRates)
{
    public string Checkout(string customer, decimal subtotal, string state)
    {
        decimal total = Math.Round(subtotal * (1 + taxRates.RateFor(state)), 2);
        return $"{customer} pays ${total} ({state})";
    }
}

public interface ITaxRates { decimal RateFor(string state); }

public class IdahoTaxRates : ITaxRates
{
    public decimal RateFor(string state) => state == "ID" ? 0.06m : 0m;
}

Output:

Jenna Morales pays $95.39 (ID)
Tyler Brooks pays $42.50 (OR)
C# primary constructor dependency injection in VS Code: OrderService(ITaxRates taxRates) is resolved from Host.CreateApplicationBuilder and prints Jenna Morales pays $95.39 (ID) and Tyler Brooks pays $42.50 (OR)
The container passes ITaxRates into the primary constructor

How does this code work?

The container finds one public constructor with an interface parameter and passes in the registered IdahoTaxRates. Jenna pays $95.39; Tyler pays $42.50 because Oregon has no sales tax.

Pro Tip: if your team wants readonly dependencies, write private readonly ITaxRates _taxRates = taxRates; and use only the field.

Primary Constructor Inheritance: Pass Arguments to the Base Class

A derived class passes its parameters to the base in the declaration, : Order(customer, subtotal). Same Order class, now as the base of a gift order:

#:property PublishAot=false
var gift = new GiftOrder("Jenna Morales", 89.99m, "Tyler Brooks");
Console.WriteLine(gift.Describe());

public class Order(string customer, decimal subtotal)
{
    public string Customer { get; } = customer;
    public decimal Subtotal { get; } = subtotal;
}

public class GiftOrder(string customer, decimal subtotal, string recipient)
    : Order(customer, subtotal)
{
    public string Describe() => $"Gift from {Customer} to {recipient}: ${Subtotal}";
}

Output:

Gift from Jenna Morales to Tyler Brooks: $89.99

How does this code work?

GiftOrder hands two parameters to the base and keeps only recipient. Describe reads the base Customer property, not the parameter. A classic derived constructor with : base(...) works too; see inheritance in C#.

Primary Constructor Warnings CS9124 and CS9107 (Double Storage)

Both warnings mean a value is stored twice, so a change to one copy never reaches the other. This code triggers both:

#:property PublishAot=false
var gift = new GiftOrder("Jenna Morales", 89.99m, "Tyler Brooks");
Console.WriteLine(gift.Label());

public class Order(string customer, decimal subtotal)
{
    public string Customer { get; } = customer;      // copy 1
    public string Shout() => customer.ToUpper();     // copy 2 -> CS9124
    public decimal Subtotal => subtotal;
}

public class GiftOrder(string customer, decimal subtotal, string recipient)
    : Order(customer, subtotal)
{
    public string Label() => $"{customer} -> {recipient}";   // CS9107
}

Output (first build):

C:\DotNetDemo\PrimaryCtorDemo\DoubleStorage.cs(7,39): warning CS9124: Parameter 'string customer' is captured into the state of the enclosing type and its value is also used to initialize a field, property, or event.
C:\DotNetDemo\PrimaryCtorDemo\DoubleStorage.cs(13,13): warning CS9107: Parameter 'string customer' 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.
Jenna Morales -> Tyler Brooks
C# primary constructor warnings in VS Code: dotnet run prints CS9124 for a parameter that initializes a property and is also captured, and CS9107 for a parameter passed to the base constructor and also used in the derived class
CS9124 and CS9107: two copies of the customer name

How does this work?

CS9124: customer initializes Customer and is also read in Shout(). CS9107: GiftOrder passes customer to the base and also reads it in Label(). The fix for both: use Customer.

Warnings only print when the file really compiles, so a cached dotnet run stays quiet.

Additional Constructors Must Call this(…)

Overloads are allowed, but each must chain to the primary constructor with : this(...). Same Order, with two overloads:

#:property PublishAot=false
Order[] orders = [new("Jenna Morales", 89.99m), new("Tyler Brooks"), new()];
foreach (var order in orders)
    Console.WriteLine(order.Describe());

public class Order(string customer, decimal subtotal)
{
    public Order(string customer) : this(customer, 0m) { }
    public Order() : this("Walk-in customer") { }

    public string Describe() => $"{customer}: ${subtotal}";
}

Output:

Jenna Morales: $89.99
Tyler Brooks: $0
Walk-in customer: $0

Drop the : this(...) and the build fails with CS8862: “A constructor declared in a type with parameter list must have ‘this’ constructor initializer.”

Classes also lose the implicit parameterless constructor, so new() needs its own overload, unlike classic constructors in C#.

Primary Constructors on Structs

Structs always keep a parameterless constructor that zeroes every field and skips your initializers. A C# struct example:

#:property PublishAot=false
Console.WriteLine(new Price(89.99m, "USD"));
Console.WriteLine(new Price());
Console.WriteLine(default(Price));

public readonly struct Price(decimal amount, string currency)
{
    public decimal Amount { get; } = amount;
    public string Currency { get; } = currency;

    public override string ToString() => $"{Amount} {Currency ?? "(null)"}";
}

Output:

89.99 USD
0 (null)
0 (null)

new Price() and default(Price) give 0 and a null currency. Add public Price() : this(0m, "USD") { } if you need a safe default.

Which Primary Constructor Approach Should You Use?

SituationUseWhy
DI service, controller, handlerPrimary constructor, parameters used directlyDependencies listed once
Value must never changeGet-only property or readonly field (Method 2)Parameters stay mutable
Data you compare or printrecordProperties, ToString, value equality
Derived class: Base(arg) in the declarationThen read base properties
Overloads with different logicClassic constructorsEvery overload must chain

Things to Keep in Mind

  • Parameters aren’t members: this.customer fails with CS1061. Expose a property if callers need it.
  • Captured parameters are mutable. Copy them to readonly members when that matters.
  • Don’t read both a copied member and its parameter; CS9124 and CS9107 flag it.
  • Every extra constructor needs : this(...) (CS8862).
  • Struct default values skip initializers and validation.

Next, the options pattern in ASP.NET Core injects settings into exactly this kind of service, and the xUnit testing guide shows how to pass a fake ITaxRates in tests.

More C# reading on classes and types:

Frequently Asked Questions

What version of C# supports primary constructors on classes?

C# 12, which ships with .NET 8. Records have had them since C# 9, and they work the same in C# 14 on .NET 10.

Are primary constructor parameters readonly?

No. Methods can assign to them. Copy the value into a readonly field or get-only property when it must not change.

Does a primary constructor create properties?

Only on a record. On a class or struct you add them yourself, for example public string Customer { get; } = customer;.

Can I use a primary constructor for dependency injection?

Yes, it’s the most common use. The DI container calls it like any other public constructor.

What does warning CS9124 mean?

A parameter both initializes a member and is captured by a method, so the value is stored twice. Microsoft lists every related diagnostic on its constructor errors page on Microsoft Learn.

Can a class have a primary constructor and other constructors?

Yes, if each one calls : this(...); otherwise you get CS8862. See the primary constructors tutorial on Microsoft Learn.