A Simpler Way to Initialize Objects

Introduction

C# 12 introduced Primary Constructors to make class and struct initialization easier, at least, that’s the idea. This feature lets you define parameters right in the class or struct definition, no need to write a separate constructor, which sounds fancy, but what does it actually mean? Basically, it cuts down on extra code and makes everything more readable. Just define the parameters upfront and use them directly inside the class. Simple, right?

In this article, we’ll dive into what primary constructors are, how they work, and why they might just be worth using - all with practical examples!

Traditional Constructor vs. Primary Constructor

Without a Primary Constructor (The Old-School Way)

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

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

Code snippet 1

This approach requires explicit constructor definition and assignment of parameters to properties. You know the usual.

With Primary Constructor. The classy way

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

Code snippet 2

  • The parameters (name and age) are directly available inside the class without needing a separate constructor.
  • This eliminates unnecessary assignments and reduces boilerplate code.

How do Primary Constructors Work?


Using Parameters Inside the Class

Primary constructor parameters are available throughout the class and can be used:

  1. To initialize properties
  2. Inside methods
  3. Within field initializers
public class Employee(string name, double salary)
{
    public string Name { get; } = name;
    public double Salary { get; } = salary;

    public void DisplayInfo()
    {
        Console.WriteLine($"Employee: {Name}, Salary: {Salary:C}");
    }
}

Code snippet 3

  • name and salary are directly accessible inside the class without needing explicit field declarations.

Primary Constructors with Structs

Primary constructors also work with structs.

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

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

Code snippet 4

Primary Constructor with Base Class Inheritance

public class Animal(string species)
{
    public string Species { get; } = species;
}

public class Dog(string name, string breed) : Animal("Dog")
{
    public string Name { get; } = name;
    public string Breed { get; } = breed;
}

// Initialization
Dog myDog = new Dog("Buddy", "Golden Retriever");

Console.WriteLine($"Name: {myDog.Name}, Breed: {myDog.Breed}, Species: {myDog.Species}");

//Output
Name: Buddy, Breed: Golden Retriever, Species: Dog

Code snippet 5

  • Here, Dog inherits from Animal, and "Dog" is passed to the base class constructor.

Advantages of Primary Constructors

  • Less Boilerplate Code: Reduces repetitive constructor code.
  • Improved Readability: Makes class definitions cleaner.
  • Better Performance: Eliminates unnecessary assignments.
  • Works with Structs and Inheritance: Simplifies initialization for data structures and base classes.

Conclusion

Primary constructors are a C# 12+ thing, giving us a cleaner, more compact way to define classes and structs. Less boilerplate, better readability, sounds like a win, right?

If you're on C# 12 or later, primary constructors might just be a nice little upgrade for your codebase, keeping things cleaner and easier to maintain.

Keep it up!

Up Next
    Ebook Download
    View all
    Learn
    View all