| Muhammad Waseem

About Newsletter
Books
30 .NET Tips
Sponsorship
Primary Constructor in C#
Jul 6, 2024
2 min read

Primary Constructor in C#

Sponsor this Newsletter

What is the primary constructor?

Primary constructors were introduced in .NET 8 and C# 12, a cleaner way of constructor initialization. We can use this syntax where we have a lot of constructor injections.

Understanding the Primary Constructor with Code

Let’s understand it with a simple example first before diving in depth. The older way of constructor injection:

public sealed class NewsletterService
{
    private readonly INewsletterRepository _newsletterRepository;

    public NewsletterService(INewsletterRepository newsletterRepository)
    {
        _newsletterRepository = newsletterRepository;
    }
}

This is how we can achieve the same with primary constructors:

internal class NewsletterService(INewsletterRepository newsletterRepository)
{
    public void Subscribe(string email)
    {
        newsletterRepository.Add(email);
    }
}

Pro(s) :

The following are the benefits of using primary constructors :

  • It removes a lot of boilerplate code.

  • Simplifies the syntax.

  • Much more readability.

This article was originally published at https://mwaseemzakir.substack.com/ on Jul 6, 2024 .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place
Previous Next

Subscribe to Newsletter

Join 9,000 Software Engineers

Buy Me a Coffee

Enjoy my articles? Support me by buying a coffee!

Buy Me a Coffee

Muhammad Waseem

Resources
  • Books
  • Courses
Newsletter
  • Articles
  • Sponsorship
Books
  • 30 .NET Tips
  • 100 .NET Tips (Soon)
Author
  • About Us
  • Contact Us
Policy
  • Privacy Policy
  • Terms and Conditions
Interview
  • C# & .NET
  • Web API

Join my .NET newsletter and stay updated!

Your Subscribe Form Embed has expired.

If you’re the owner of this site, please create your new embed on Supascribe.

Create New Embed →
;

© 2025 Muhammad Waseem. All rights reserved.