Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 182 ยท Classes and Objects

Primary Constructors

Learn C# 12 primary constructors for classes and structs - captured parameters, initializers, validation, how they differ from records, dependency injection use and when to avoid them.

Look at almost any C# class that receives its dependencies or data through a constructor and you see the same boring ritual: declare a field, declare a constructor parameter, assign one to the other. Three lines of ceremony for every value. Primary constructors, added to classes and structs in C# 12 (.NET 8), remove most of it. You put the parameter list right on the type declaration, and those parameters are available throughout the class body.

They look like a small shortcut, but they have subtle rules that surprise people: the parameters are not properties, they are captured by the compiler only if you use them, and they are mutable by default. This lesson explains exactly how they work, how they differ from records, and where they shine and where they do not.

The idea

Compare the traditional style with the primary constructor style:

C#
// Before: explicit field, parameter, assignment
class Greeter
{
    private readonly string _greeting;

    public Greeter(string greeting)
    {
        _greeting = greeting;
    }

    public string Greet(string name) => $"{_greeting}, {name}!";
}

// After: a primary constructor
class Greeter(string greeting)
{
    public string Greet(string name) => $"{greeting}, {name}!";
}

The parameter list after the class name is the constructor. Inside the class, greeting is usable in methods, property initializers and field initializers. You create the object exactly as before: new Greeter("Hello").

C# Your first primary constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Parameters are not properties

This is the first thing to get right. In a record, record Person(string Name) creates a public property Name. In a class or struct primary constructor, the parameter creates nothing public. If a method uses the parameter, the compiler quietly stores it in a hidden private field (we say the parameter is captured). If no member uses it, nothing is stored at all.

C# A parameter is not a public member (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler answers with error CS1061: 'Greeter' does not contain a definition for 'greeting' and no accessible extension method 'greeting' accepting a first argument of type 'Greeter' could be found. If you want the value visible outside, expose it with a property that is initialized from the parameter:

C# Exposing a parameter as a property

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

In Product, Name and Price copy the parameter values at construction time, and Label() reads the properties. The parameters are used only once, to initialize. Had Label() used the raw parameters name and price as well, the compiler would store hidden captured copies next to the properties and warn with 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. Two copies of one value can drift apart, so the guideline is to use a parameter either to initialize a property/field or directly in methods, never both.

Where parameters can be used

Primary constructor parameters are in scope in:

  • Field and property initializers (as above).
  • Method, property and accessor bodies.
  • Other constructors? Yes, but those must call the primary one with this(...).

They are not in scope as this.name (there is no member of that name). They are also not usable in static members, because those have no instance.

Other constructors must chain

If you declare additional constructors in a class with a primary constructor, each must start with : this(...), so that the primary one always runs.

C# Extra constructors chain to the primary one

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Validation and mutability

Two traps appear immediately.

1. There is no body to validate in. A traditional constructor can throw when it gets bad data. A primary constructor has no body, so you validate in the initializer expression that uses the parameter, using a helper:

C# Validating primary constructor parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

If you need several steps of validation, use a normal constructor instead. That is a legitimate and common choice.

2. Parameters are mutable. Unlike a readonly field, a captured parameter can be reassigned inside the class. Nothing stops a method from writing greeting = "oops";. Be careful, especially when the parameter is also used to initialize a property, because then the two silently diverge.

C# Captured parameters are mutable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

That compiles and works, but a reader may not expect a constructor parameter to behave as a field. If you need mutable state, declare an explicit field so the intent is visible. If you want immutability, copy into a readonly field:

C#
class Counter(int start)
{
    private readonly int _start = start;   // immutable copy, original parameter unused later
}

Primary constructors on structs

Structs support the same syntax (C# 12). Remember that structs are copied by value. A captured parameter is stored inside each copy.

C# A struct with a primary constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

For a plain value type that is only data, a readonly record struct is often even shorter, and it gives you equality and ToString for free (see Records and Structs).

Primary constructors versus records

Both put a parameter list on the type, which causes confusion. The differences are important:

class C(int x) record C(int X)
Parameter creates a public property No Yes (init-only by default)
Value-based equality No (reference equality) Yes
ToString, with, deconstruction No Yes, generated
Parameters mutable inside Yes The generated property is init-only
Intended for Services, behaviour-rich types Data, DTOs, value objects

Rule of thumb: records model data; classes with primary constructors model behaviour that needs a few dependencies.

Primary constructors and dependency injection

The most popular use is injecting services. Instead of a field per dependency plus a constructor, you declare them once. Here the services are hand-rolled interfaces so the example runs anywhere; with ASP.NET Core's container the pattern is identical.

C# Injecting dependencies with a primary constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The class stays focused on behaviour. The dependencies are plain, non-public, and only exist because a method used them. More about this style in the dependency injection chapter. One more warning: do not combine this with exposing the captured parameter through a base class constructor as well; the compiler warns (CS9107) when a parameter is both passed to the base constructor and captured, because it would be stored twice.

When to use, when to avoid

Use a primary constructor when:

  • The class receives a handful of dependencies or values and just uses them.
  • You would otherwise write field-and-assign boilerplate.
  • No validation beyond a null/range check is needed.

Prefer a traditional constructor when:

  • You need to validate with several statements, or do other work at construction.
  • You want a readonly field for guaranteed immutability.
  • Readers may be confused by hidden captured state.
  • The type is mostly data (use a record).

Common mistakes

  • Expecting a public property. In classes and structs the parameter is not a member.
  • Initializing a property and also reading the raw parameter. You get two copies that can drift apart.
  • Forgetting : this(...) on extra constructors. Error CS8862 reminds you.
  • Treating parameters as read-only. They are not, unless you copy them to a readonly field.
  • Using them in static members. Parameters are instance-only.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In class Greeter(string greeting), what is greeting?

    Class primary constructor parameters are not members. The compiler stores a hidden field only if a member uses them, and that field is mutable.
  2. 2. What is the main difference between class P(string Name) and record P(string Name)?

    Records turn positional parameters into properties and add equality, ToString and with-expressions. Class parameters stay private.
  3. 3. Which statement is required on an extra constructor in a class that has a primary constructor?

    Every other constructor must chain to the primary constructor so its parameters are always supplied.
  4. 4. Which is a good reason to prefer a traditional constructor?

    A primary constructor has no body, so complex validation or setup belongs in a normal constructor.
  5. 5. What happens when a method assigns start = 5; to a primary constructor parameter?

    Captured parameters are ordinary mutable state. Copy into a readonly field if you want immutability.

Summary

  • C# 12 lets classes and structs declare a primary constructor: class Service(IClock clock).
  • The parameters are in scope in the whole class body but are not members; unused ones cost nothing, used ones become hidden mutable fields.
  • Expose a value by initializing a property from the parameter; avoid using both the property and the raw parameter.
  • There is no constructor body, so validate through helper expressions or choose a normal constructor.
  • Extra constructors must chain with : this(...).
  • Records use the same syntax but generate properties and equality: records for data, primary-constructor classes for behaviour with dependencies.

Next: Static Members and Static Classes