C# primary constructors: quick examples

Posted: (EET/GMT+2)

 

Microsoft released .NET 8 and C# version 12 about a year ago. One of the new features introduces was the support for primary constructors, which simplify how you declare and initialize classes that mainly act as data holders or simple services. Instead of repeating constructor parameters and fields, you can define them directly in the class declaration.

Here is a classic way to define an instance constructor:

public class Person
{
    public string Name { get; }
    public int Age { get; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

With a primary constructor, the class becomes more compact:

public class Person(string name, int age)
{
    public string Name { get; } = name;
    public int Age { get; } = age;
}

This is especially nice for simple types where the constructor just forwards values into properties. It also works well with dependency injection scenarios. For example:

public class ReportService(ILogger<ReportService> logger, HttpClient client)
{
    public void RunReport()
    {
        logger.LogInformation("Running report...");
        // use client...
    }
}

You don't need to declare fields or a full constructor body if all you want to do is have DI assign the dependencies.

Primary constructors are not required in any application, but they help keep small classes concise, especially in modern .NET applications where you have many "thin" services. They're one of those features that quietly reduce boilerplate over time.