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#: Use Record Types for Immutable Data Objects

- 30.03.26 - ErcanOPAK

📦 Value Objects Made Easy

DTOs with 50 lines of boilerplate? Equals(), GetHashCode(), ToString()? Record types (C# 9+) are immutable, value-based, with auto-generated methods. One line replaces 50.

Traditional Class vs Record

// ❌ Traditional class - Lots of boilerplate
public class PersonClass
{
    public string Name { get; init; }
    public int Age { get; init; }
    
    public PersonClass(string name, int age)
    {
        Name = name;
        Age = age;
    }
    
    // Manual Equals
    public override bool Equals(object? obj)
    {
        if (obj is not PersonClass other) return false;
        return Name == other.Name && Age == other.Age;
    }
    
    // Manual GetHashCode
    public override int GetHashCode()
    {
        return HashCode.Combine(Name, Age);
    }
    
    // Manual ToString
    public override string ToString()
    {
        return $"PersonClass {{ Name = {Name}, Age = {Age} }}";
    }
    
    // Manual copy with changes
    public PersonClass WithAge(int newAge)
    {
        return new PersonClass(Name, newAge);
    }
}

// 40+ lines for simple data object!

// ✅ Record - One line!
public record Person(string Name, int Age);

// That's it! Auto-generates:
// - Constructor
// - Properties (init-only)
// - Equals() and GetHashCode() (value-based)
// - ToString()
// - Deconstruct()
// - With expressions

🎯 Record Features

public record Person(string Name, int Age);

// Value-based equality
var person1 = new Person("Alice", 30);
var person2 = new Person("Alice", 30);

Console.WriteLine(person1 == person2);  // True! (value equality)
// With classes: False (reference equality)

// Auto ToString()
Console.WriteLine(person1);  // Person { Name = Alice, Age = 30 }

// With expressions (non-destructive mutation)
var person3 = person1 with { Age = 31 };
Console.WriteLine(person3);  // Person { Name = Alice, Age = 31 }
// person1 unchanged (immutable)

// Deconstruction
var (name, age) = person1;
Console.WriteLine($"{name} is {age}");  // Alice is 30

// Pattern matching
var message = person1 switch
{
    { Age: < 18 } => "Minor",
    { Age: >= 18 and < 65 } => "Adult",
    _ => "Senior"
};

Record vs Record Struct vs Class

// Record (reference type, immutable by default)
public record Person(string Name, int Age);

// Record struct (value type, C# 10+)
public record struct Point(int X, int Y);

// Class (reference type, mutable)
public class PersonClass
{
    public string Name { get; set; }
    public int Age { get; set; }
}

// When to use what?
// Record: DTOs, value objects, immutable data
// Record struct: Small data (< 16 bytes), high-performance scenarios
// Class: Entities with behavior, mutable state

Advanced Record Features

// Additional properties and methods
public record Person(string Name, int Age)
{
    // Computed property
    public string DisplayName => $"{Name} ({Age})";
    
    // Validation
    public Person
    {
        if (Age < 0) throw new ArgumentException("Age cannot be negative");
    }
    
    // Additional methods
    public bool IsAdult() => Age >= 18;
}

// Inheritance (records can inherit from records)
public record Employee(string Name, int Age, string Department) 
    : Person(Name, Age);

var emp = new Employee("Bob", 25, "IT");
Console.WriteLine(emp);  
// Employee { Name = Bob, Age = 25, Department = IT }

// With expression works with derived records
var emp2 = emp with { Department = "HR" };

🌐 Perfect for DTOs

// API Request/Response DTOs
public record CreateUserRequest(
    string Email,
    string Name,
    string Password
);

public record UserResponse(
    int Id,
    string Email,
    string Name,
    DateTime CreatedAt
);

// API Controller
[HttpPost("users")]
public async Task CreateUser(CreateUserRequest request)
{
    var user = await _userService.CreateAsync(request);
    return new UserResponse(
        user.Id,
        user.Email,
        user.Name,
        user.CreatedAt
    );
}

// Clean, immutable, perfect for data transfer

Positional vs Nominal Records

// Positional record (concise)
public record Person(string Name, int Age);

// Nominal record (traditional property syntax)
public record Person
{
    public string Name { get; init; }
    public int Age { get; init; }
}

// Mix both
public record Person(string Name, int Age)
{
    public string Email { get; init; } = string.Empty;
    public DateTime CreatedAt { get; init; } = DateTime.UtcNow;
}

var person = new Person("Alice", 30)
{
    Email = "alice@example.com"
};

✅ Benefits of Records

  • Less code: 90% less boilerplate than classes
  • Immutable by default: Thread-safe, predictable
  • Value semantics: Equality based on data, not reference
  • With expressions: Easy non-destructive updates
  • Pattern matching: Works beautifully with switch
  • Auto ToString(): Great for debugging

💡 Best Practices

  • Use for DTOs: API requests/responses, messages
  • Use for value objects: Money, Address, Coordinate
  • Add validation: In constructor or properties
  • Keep immutable: Use init, not set
  • Prefer positional: More concise for simple records

🎯 Real-World Example

// Domain value objects
public record Money(decimal Amount, string Currency)
{
    public Money Add(Money other)
    {
        if (Currency != other.Currency)
            throw new InvalidOperationException("Currency mismatch");
        return this with { Amount = Amount + other.Amount };
    }
}

public record Address(
    string Street,
    string City,
    string State,
    string ZipCode,
    string Country
);

public record CustomerDto(
    int Id,
    string Name,
    Address Address,
    Money Balance
);

// Usage
var addr = new Address("123 Main St", "NYC", "NY", "10001", "USA");
var balance = new Money(1000m, "USD");
var customer = new CustomerDto(1, "Alice", addr, balance);

// Update address
var updated = customer with 
{ 
    Address = customer.Address with { City = "Boston" }
};

// Value equality
var addr2 = new Address("123 Main St", "NYC", "NY", "10001", "USA");
Console.WriteLine(addr == addr2);  // True!

"Converted all DTOs from classes to records. Deleted 2000+ lines of boilerplate. Bugs related to mutable state disappeared. API responses now immutable, thread-safe. Should've used records from day one."

— .NET Developer

Related posts:

C#: Use ValueTuple for Lightweight Multiple Return Values

C#: Use ValueTuple for Lightweight Multiple Return Values

C#: Use Default Interface Methods for API Evolution

C#: Use Default Interface Methods for API Evolution

C#: Use Raw String Literals for Multi-line Strings and JSON

C#: Use Raw String Literals for Multi-line Strings and JSON

Views: 16

Post navigation

SQL: Use CTEs for Readable Complex Queries
C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions

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