.NET Framework, Software Development

What is a Primary Constructor in C#?

Primary constructors are a new feature in C# that simplifies the declaration and initialization of class properties. By enabling a more concise syntax, developers can increase readability and reduce boilerplate code.

We have had primary constructors available since C# 9 however they were only available for Records but with C# 12 they’ll be added to classes and structs.

Primary constructors allow developers to define properties directly within the class header, rather than creating a separate constructor method. This streamlined syntax not only makes the code cleaner but also promotes a better understanding of the class’s purpose and structure.

For instance, instead of writing:

class Person
{
    public string FirstName { get; }
    public string LastName { get; }

    public Person(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}

With primary constructors, you can now write:

class Person(string firstName, string lastName)
{
    public string FirstName { get; } = firstName;
    public string LastName { get; } = lastName;
}

Primary constructors are expected to become a popular feature among C# developers (at least, I’ll be happy with it), facilitating more efficient and maintainable code.