C# 13: Primary Constructors for All Classes and a New Lock Type

C# 13: Primary Constructors for All Classes and a New Lock Type

C# 13: Primary Constructors for All Classes and a New Lock Type

C# 13 ships with .NET 9 and refines the primary constructor feature introduced in C# 12, while adding a new System.Threading.Lock type for safer concurrent code.

Primary Constructors Expanded

Primary constructors now work on all class and struct types. Parameters are in scope throughout the entire class body:

public class OrderService(IRepository repo, ILogger<OrderService> logger)
{
    public async Task<Order> GetOrderAsync(int id)
    {
        logger.LogInformation("Fetching order {Id}", id);
        return await repo.FindAsync<Order>(id);
    }
}

New Lock Type

// Old approach
private readonly object _syncRoot = new();
lock (_syncRoot) { /* ... */ }

// C# 13
private readonly Lock _lock = new();
lock (_lock) { /* ... */ }

The compiler recognises Lock specifically and uses optimised EnterScope() semantics instead of Monitor.Enter/Exit, reducing overhead.

params Collections

void PrintAll(params IEnumerable<string> items) { /* ... */ }
void LogValues(params ReadOnlySpan<int> values) { /* ... */ }
All Comments