Primary constructors are one of the most useful features introduced in C# 12 using the latest Visual Studio 2022 version or the .NET 8 SDK. They reduce constructor boilerplate, especially in Dependency Injection (DI) scenarios, making your code cleaner without changing how objects are created.
What is a Primary Constructor?
A Primary Constructor lets you declare constructor parameters directly in the class declaration.
Before C# 12
public class OrderService
{
private readonly ILogger<OrderService> _logger;
public OrderService(ILogger<OrderService> logger)
{
_logger = logger;
}
public void Process()
{
_logger.LogInformation("Processing...");
}
}
C# 12
public class OrderService(ILogger<OrderService> logger)
{
public void Process()
{
logger.LogInformation("Processing...");
}
}
Less code, same behavior.
Why Use Primary Constructors?
Instead of writing repetitive constructor assignments, Primary Constructors allow you to:
- Reduce boilerplate code
- Simplify Dependency Injection
- Improve readability
- Encourage immutable designs
- Keep service classes concise
How It Works Internally
Primary Constructor parameters are available throughout the class.
public class Employee(string name)
{
public void Print()
{
Console.WriteLine(name);
}
}
Important
Primary Constructor parameters are not automatically converted into properties or fields.
If you want a public property, create one explicitly.
public class Employee(string name)
{
public string Name => name;
}
The compiler creates hidden storage only when required, avoiding unnecessary memory allocation.
Real-World Example (Dependency Injection)
One of the best use cases is constructor injection.
public class EmailService(
ILogger<EmailService> logger,
IEmailRepository repository)
{
public void Send()
{
logger.LogInformation("Sending email...");
repository.Save();
}
}
This is much cleaner than traditional constructor injection.
Performance
There is no significant performance improvement.
The generated IL is nearly identical to a traditional constructor.
The primary benefit is:
- Better readability
- Less boilerplate
- Easier maintenance
Best Practices
- ✔ Use Primary Constructors for service classes and DI.
- ✔ Expose properties explicitly when needed.
- ✔ Keep constructor logic simple.
- ✔ Validate critical parameters before using them.
- ✔ Prefer them for immutable objects.
Common Mistakes
- ❌ Assuming constructor parameters become public properties.
- ❌ Creating unnecessary backing fields.
- ❌ Using Primary Constructors for complex initialization logic.
- ❌ Confusing them with Records, which automatically generate properties.
Quick Revision
- Introduced in C# 12
- Constructor parameters are declared in the class declaration
- Parameters are accessible throughout the class
- Parameters are not automatically properties
- Ideal for Dependency Injection
- Runtime performance is almost identical to traditional constructors
- Best suited for service classes and clean architecture
Final Thoughts
Primary Constructors are a developer productivity feature, not a performance feature. They eliminate repetitive constructor code, making modern C# applications cleaner and easier to maintain. For senior developers, the key is knowing when to use them—primarily in dependency injection scenarios and immutable designs—while avoiding unnecessary complexity in classes that require extensive initialization logic.
FAQs | Interview Questions
Q. What problem do Primary Constructors solve?
They reduce constructor boilerplate while keeping object initialization clean, especially for Dependency Injection.
Q. Do they automatically create properties?
No. Only records do that.
Q. Do they improve performance?
No. The benefit is cleaner, more maintainable code—not faster execution.
Q. When should you use them?
For DI-heavy classes, services, background workers, and lightweight immutable types.
No comments:
Post a Comment