Primary Constructors

Today at work, during a pull request review, I stumbled across a feature in .NET 8. It’s called primary constructors, and it’s part of the updates in C# 12. If you’ve ever been annoyed by writing repetitive boilerplate for constructors in your classes or structs, you’re going to love this! This little feature streamlines dependency injection and makes initialization cleaner than ever. Let me show you what I’ve learned and how it can make your code more elegant.

Simplifying Class Initialization with Primary Constructors in .NET 8

This approach allows you to declare a primary constructor directly in the class definition, eliminating the need to manually define a separate constructor for dependency injection.

public class TestController(ILogger logger) : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        var tests = GetTests();
        logger.LogInformation($"These are the tests: {tests}");
        return Ok(tests);
    }
}

Benefits and Drawbacks of Using Primary Constructors in a Class

Utilizing this feature brings some pros and cons to it. Let’s have a look at what these are:

Pros

  • Direct declaration of dependencies in the class signature improves code clarity
  • Eliminates the need for explicit property initialization

Cons

  • Parameters are not automatically assigned to readonly fields; manual assignment is required
  • Complex logic in initialization can reduce the readability of primary constructors

Manually Setting Dependencies to readonly in a Class

When the need arises to have the dependency set to readonly, we need to set this manually:

public class TestController(ILogger logger) : ControllerBase
{
    // Explicitly assign the parameter to a readonly field
    private readonly ILogger _logger = logger;

    [HttpGet]
    public IActionResult Get()
    {
        var tests = GetTests();
        _logger.LogInformation($"These are some new tests: {tests}");
        return Ok(tests);
    }
}

This is because a class cannot be set as readonly. However, when working with a struct it’s a different story.

Using Primary Constructor in a Struct

When working with a struct, we can set the struct to readonly. This is because struct ensures immutability and it guarantees that:

  • All fields within the struct are implicitly readonly
  • The struct itself cannot modify its state after being constructed
public readonly struct Pointer(double x, double y)

Conclusion

So this was part of what I have learned today. I wanted to keep on writing about structs, but I was getting into how they work, their performance, etc.. and I was getting a bit off-topic. So, I’ve decided to continue writing about them in a different post 🙂