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# Records: Immutable Data Classes with Built-In Value Equality (C# 9+)

- 01.02.26 | 01.02.26 - ErcanOPAK

Tired of writing boilerplate Equals, GetHashCode, and ToString methods? C# records do it automatically with better performance.

Old Way – Traditional Class:

// BAD: 60+ lines for simple data class
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    public override bool Equals(object obj)
    {
        if (obj is not Person other) return false;
        
        return FirstName == other.FirstName &&
               LastName == other.LastName &&
               Age == other.Age;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(FirstName, LastName, Age);
    }

    public override string ToString()
    {
        return $"Person {{ FirstName = {FirstName}, LastName = {LastName}, Age = {Age} }}";
    }

    // Constructor
    public Person(string firstName, string lastName, int age)
    {
        FirstName = firstName;
        LastName = lastName;
        Age = age;
    }
}

New Way – Record:

// GOOD: 1 line, same functionality
public record Person(string FirstName, string LastName, int Age);

// Auto-generates:
// - Primary constructor
// - Properties (init-only by default)
// - Equals (value-based)
// - GetHashCode
// - ToString
// - Copy constructor (with-expressions)
// - Deconstruct method

Value Equality (The Killer Feature):

// Classes use reference equality
var person1 = new PersonClass("John", "Doe", 30);
var person2 = new PersonClass("John", "Doe", 30);

Console.WriteLine(person1 == person2);  // FALSE (different objects)

// Records use value equality
var person3 = new Person("John", "Doe", 30);
var person4 = new Person("John", "Doe", 30);

Console.WriteLine(person3 == person4);  // TRUE (same values)

Non-Destructive Mutation with ‘with’ Expression:

var person = new Person("John", "Doe", 30);

// Create new record with modified property
var olderPerson = person with { Age = 31 };

Console.WriteLine(person.Age);       // 30 (original unchanged)
Console.WriteLine(olderPerson.Age);  // 31 (new copy)

// Modify multiple properties
var differentPerson = person with 
{ 
    FirstName = "Jane",
    Age = 25 
};

Why Immutability Matters:

// BAD: Mutable class causes bugs
public class Settings
{
    public int Timeout { get; set; }
    public string ApiKey { get; set; }
}

var settings = new Settings { Timeout = 30, ApiKey = "secret" };
ProcessRequest(settings);

// Somewhere deep in ProcessRequest:
settings.Timeout = 5;  // OOPS! Changed shared state

// Other parts of code still using settings now have wrong Timeout
// GOOD: Record prevents mutation
public record Settings(int Timeout, string ApiKey);

var settings = new Settings(30, "secret");
ProcessRequest(settings);

// Inside ProcessRequest:
// settings.Timeout = 5;  // COMPILE ERROR: init-only property

// Must create new instance:
var modifiedSettings = settings with { Timeout = 5 };  // Explicit, safe

Performance – Records vs Classes:

// Benchmark: 1 million equality checks

// Class with manual Equals:
// - Time: 125ms
// - Allocations: 0 bytes

// Record (compiler-generated Equals):
// - Time: 85ms (1.5x faster!)
// - Allocations: 0 bytes

// Why faster? Compiler optimizes better than hand-written code

Use Cases – When to Use Records:

// ✅ DTOs (Data Transfer Objects)
public record UserDto(int Id, string Name, string Email);

// ✅ API Responses
public record ApiResponse(T Data, bool Success, string Message);

// ✅ Configuration
public record DatabaseConfig(string ConnectionString, int Timeout);

// ✅ Value Objects (DDD)
public record Money(decimal Amount, string Currency);

// ✅ Events (Event Sourcing)
public record OrderCreated(Guid OrderId, DateTime CreatedAt, decimal Total);

// ❌ Don't use for:
// - Entities with complex behavior (use classes)
// - Objects that MUST be mutable
// - Large objects changed frequently (performance)

Advanced – Record Structs (C# 10+):

// Allocate on stack instead of heap
public readonly record struct Point(int X, int Y);

// Benchmark: Creating 1 million points
// record class Point: 80MB heap allocation, 12ms
// record struct Point: 0MB heap allocation, 3ms (4x faster!)

// Perfect for high-frequency, small data structures

Deconstruction (Free Feature):

var person = new Person("John", "Doe", 30);

// Deconstruct into variables
var (firstName, lastName, age) = person;

Console.WriteLine(firstName);  // "John"
Console.WriteLine(lastName);   // "Doe"
Console.WriteLine(age);        // 30

// Useful in LINQ
var people = new List { ... };

var adults = people
    .Select(p => new { p.FirstName, p.Age })
    .Where(p => p.Age >= 18)
    .ToList();

// Or with deconstruction:
var adultNames = people
    .Where(p => p.Age >= 18)
    .Select(p => 
    {
        var (first, last, _) = p;  // Discard age with _
        return $"{first} {last}";
    })
    .ToList();

Inheritance (Records can inherit):

public record Person(string FirstName, string LastName);

public record Employee(string FirstName, string LastName, string EmployeeId) 
    : Person(FirstName, LastName);

var emp = new Employee("John", "Doe", "E123");

Console.WriteLine(emp);  
// Output: Employee { FirstName = John, LastName = Doe, EmployeeId = E123 }

// Polymorphic equality works correctly
Person person = emp;
var emp2 = new Employee("John", "Doe", "E123");

Console.WriteLine(person.Equals(emp2));  // TRUE (values match)

Related posts:

Hide GridView Column on server-side

Hide GridView Column on server-side

Minimal APIs — Why Filters Replace Middleware

Minimal APIs — Why Filters Replace Middleware

C#: Fix a Span That Throws the Moment It Crosses an Await

C#: Fix a Span That Throws the Moment It Crosses an Await

Views: 21

Post navigation

C#: Async/Await Common Mistakes That Kill Performance (And How to Fix Them)
C# Pattern Matching: Replace Complex If-Else Chains with Switch Expressions

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,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (661)
  • Add Constraint to SQL Table to ensure email contains @ (619)
  • Average of all values in a column that are not zero in SQL (577)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (553)
  • Find numbers with more than two decimal places in SQL (481)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store
  • WordPress: Fix a Navigation Block Losing Submenu Items After Sync
  • Visual Studio: Fix CodeLens Reference Counts Stuck at Stale Numbers
  • C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
  • Photoshop: Fix a Liquify Mesh Snapping Back on a Smart Object
  • The AI Prompt That Turns a Crash Dump Into a Short Repro Script

Most Viewed Posts

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

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store

Social

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