What is the primary constructor?
Understanding with example
Benefits of using them
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
Whenever you’re ready, there are 2 ways I can help you:
If you want to boost your .NET skills and do some code in action you can do that by subscribing to my YouTube Channel
Promote yourself to 10400+ subscribers by sponsoring this newsletter
Patreon Community: Join and gain access to the 200+ articles I have published so far in one place. Join here