Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C# Record Types: Immutable Data Patterns That Eliminate Bugs

- 05.02.26 - ErcanOPAK

Mutable objects causing threading issues? C# 9+ records provide immutable data structures with built-in value semantics.

Records vs Classes: When to Use Each

// Use RECORDS for:
// 1. Immutable data transfer objects (DTOs)
// 2. Value objects in domain-driven design
// 3. Configuration objects
// 4. API request/response models
// 5. Event objects in event sourcing

// Use CLASSES for:
// 1. Entities with identity and mutation
// 2. Services with behavior
// 3. Complex objects with inheritance hierarchies
// 4. Objects needing custom equality semantics
// 5. Framework base classes

// Example: Record for API response
public record ApiResponse(
    T Data,
    bool Success,
    string Message,
    DateTime Timestamp = default)
{
    public DateTime Timestamp { get; init; } = Timestamp == default 
        ? DateTime.UtcNow 
        : Timestamp;
}

// Usage:
var response = new ApiResponse(
    Data: product,
    Success: true,
    Message: "Product retrieved successfully");
    
// Immutable - cannot modify after creation
// Value equality - two responses with same data are equal
// Built-in ToString() with property values
// Deconstruction support

Advanced Record Patterns:

// Positional record (immutable by default)
public record Person(
    string FirstName,
    string LastName,
    int Age);

// With non-positional properties
public record Employee : Person
{
    public string EmployeeId { get; init; }
    public decimal Salary { get; init; }
    public Department Department { get; init; }
    
    public Employee(
        string firstName,
        string lastName,
        int age,
        string employeeId,
        decimal salary,
        Department department)
        : base(firstName, lastName, age)
    {
        EmployeeId = employeeId;
        Salary = salary;
        Department = department;
    }
}

// Record struct (C# 10+)
public readonly record struct Point(
    double X,
    double Y)
{
    public double DistanceFromOrigin => Math.Sqrt(X * X + Y * Y);
}

// With validation in init-only setters
public record OrderItem
{
    private int _quantity;
    private decimal _price;
    
    public int Quantity
    {
        get => _quantity;
        init
        {
            if (value <= 0)
                throw new ArgumentException("Quantity must be positive");
            _quantity = value;
        }
    }
    
    public decimal Price
    {
        get => _price;
        init
        {
            if (value < 0)
                throw new ArgumentException("Price cannot be negative");
            _price = value;
        }
    }
    
    public decimal Total => Quantity * Price;
}

Related posts:

Improve .NET Logging with Structured Log Messages

Improve .NET Logging with Structured Log Messages

C#: Enable Nullable Reference Types to Prevent NullReferenceException

C#: Enable Nullable Reference Types to Prevent NullReferenceException

C#: Clean Metadata with Generic Attributes

C#: Clean Metadata with Generic Attributes

Views: 16

Post navigation

.NET Core Middleware Magic: How to Build Pipeline Filters That Transform Your API
Ajax Revolution: How Fetch API and Async/Await Replace jQuery.ajax()

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (547)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com