C# 12/13 Primary Constructors for Classes & Structs
1Concept
Primary constructors allow parameters directly in the class or struct definition header, serving as constructor parameters that can directly initialize fields, properties, or base classes.
2Architecture Diagram
public class PaymentGateway(string apiKey, HttpClient client)
│
Directly captures dependencies into private state
│
No boilerplate boilerplate private readonly fields needed!3Code Example
C# 13 & .NET 9
using System;
using System.Net.Http;
public class OrderService(string tenantCode, int timeoutSeconds)
{
public void ProcessOrder(int orderId)
{
Console.WriteLine($"[Tenant: {tenantCode}] Processing Order #{orderId} with Timeout: {timeoutSeconds}s");
}
}
public class PrimaryConstructorDemo
{
public static void Main()
{
var svc = new OrderService("EU_CORP", 30);
svc.ProcessOrder(9082);
}
}4Expected Output
[Tenant: EU_CORP] Processing Order #9082 with Timeout: 30s
5Key Takeaways
- ✓Primary constructors significantly reduce boilerplate in dependency injection.
- ✓Parameters are in scope throughout the class body.
- ✓If you need public properties, use records or explicit property initialization.