Skip to main content

Lesson 2 of 9

Modern C# 12 - Records, Primary Constructors & Required Members

C# 12 brings major ergonomic improvements to how you define types. Records, primary constructors, and required members reduce boilerplate dramatically - especially important for DTOs, commands, and domain entities in ASP.NET Core backends.

30 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Records - Immutable Data Types

Records - Immutable Data Types
// ━━ Records: immutable, value-equality, built for data ━━
// Perfect for: DTOs, API request/response models, CQRS commands/queries

// Record with positional syntax - generates constructor, deconstruct, ==, ToString
public record CreateProductRequest(
    string Name,
    decimal Price,
    int StockQuantity,
    string CategoryId
);

// Record with body - mix positional + computed props
public record ProductResponse(string Id, string Name, decimal Price)
{
    // Computed property - executed on every access
    public string FormattedPrice => Price.ToString("C");
    // Additional validation
    public bool IsInStock { get; init; } // init-only - settable only in object initializer
}

// ━━ Record structs (.NET 6+) - stack-allocated, value semantics ━━
// Use for high-frequency, small data: coordinates, money, IDs
public readonly record struct Money(decimal Amount, string Currency)
{
    public static Money Zero(string currency) => new(0m, currency);
    public Money Add(Money other)
    {
        if (Currency != other.Currency)
            throw new InvalidOperationException("Currency mismatch");
        return this with { Amount = Amount + other.Amount };
    }
}

// ━━ Non-destructive mutation with 'with' expression ━━
var original = new CreateProductRequest("Widget", 9.99m, 100, "cat-1");
var updated = original with { Price = 12.99m }; // creates new record, rest same

// ━━ Value equality (vs reference equality for classes) ━━
var req1 = new CreateProductRequest("Widget", 9.99m, 100, "cat-1");
var req2 = new CreateProductRequest("Widget", 9.99m, 100, "cat-1");
Console.WriteLine(req1 == req2); // true - compares values, not references

Primary Constructors (C# 12) & Required Members

Primary Constructors (C# 12) & Required Members
// ━━ Primary constructors (C# 12) - class/struct, not just records ━━
// Parameters become captured values, not auto-properties

public class ProductService(
    IProductRepository repository,   // injected via DI
    ILogger<ProductService> logger,
    IMemoryCache cache)
{
    // Parameters are in scope for the whole class body
    public async Task<Product?> GetByIdAsync(string id, CancellationToken ct = default)
    {
        return await cache.GetOrCreateAsync($"product:{id}", async entry =>
        {
            entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
            logger.LogInformation("Cache miss for product {ProductId}", id);
            return await repository.FindByIdAsync(id, ct);
        });
    }
}

// ━━ Required members (C# 11+) - compile-time enforcement ━━
// Ensures properties are always set - replaces constructor overloads for config

public class EmailSettings
{
    public required string SmtpHost { get; init; }
    public required int Port { get; init; }
    public required string FromAddress { get; init; }
    public bool UseSsl { get; init; } = true; // optional with default

    // CS8618 compile error if you forget required member in object initializer:
    // var bad = new EmailSettings { SmtpHost = "smtp.example.com" }; ← missing Port, FromAddress
}

// Correct:
var settings = new EmailSettings
{
    SmtpHost = "smtp.example.com",
    Port = 587,
    FromAddress = "noreply@example.com"
};

Tip

Tip

Practice Modern C 12 Records Primary Constructors Required Members in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Modern C 12 Records Primary Constructors Required Members from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Modern C 12 Records Primary Constructors Required Members is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/9 done