Writing constructors with property assignment is repetitive. C# 12 primary constructors simplify it.
Old Way:
public class ProductService
{
private readonly ILogger _logger;
private readonly IProductRepository _repo;
public ProductService(ILogger logger, IProductRepository repo)
{
_logger = logger;
_repo = repo;
}
public void DoWork()
{
_logger.LogInfo("Working");
_repo.Save();
}
}
Primary Constructor (C# 12):
public class ProductService(ILogger logger, IProductRepository repo)
{
public void DoWork()
{
logger.LogInfo("Working"); // Directly accessible!
repo.Save();
}
}
// Parameters become fields automatically
// No manual property assignment needed
With Properties:
public class Person(string firstName, string lastName, int age)
{
public string FullName => $"{firstName} {lastName}";
public bool IsAdult => age >= 18;
}
var person = new Person("John", "Doe", 30);
Console.WriteLine(person.FullName); // "John Doe"
Less boilerplate, same functionality!
