Records were introduced in C# 9.0 as a special kind of reference type designed to make it easier to work with immutable data and provide built-in value-based equality. This guide explains everything you need to know about records in C#, with practical examples.
A record is a reference type like a class, but it compares instances by value rather than by reference. It’s ideal for scenarios like DTOs, configuration models, or read-only data structures.
public record Person(string FirstName, string LastName);
var p1 = new Person("John", "Doe");
var p2 = new Person("John", "Doe");
Console.WriteLine(p1 == p2); // True
public record Car
{
public string Brand { get; init; }
public string Model { get; init; }
}
var car1 = new Car { Brand = "Toyota", Model = "Corolla" };
with
expression for cloninginit
init
vs set
init
allows assignment only during object creation, ensuring immutability after initialization.
public class Person
{
public string FirstName { get; init; }
}
var p = new Person { FirstName = "John" };
p.FirstName = "Mark"; // ❌ Error
with
Expressionvar car2 = car1 with { Model = "Camry" };
Positional records support automatic deconstruction:
var (first, last) = new Person("John", "Doe");
For regular records or classes, define manually:
public void Deconstruct(out string brand, out string model)
{
brand = Brand;
model = Model;
}
public record Person(string FirstName, string LastName = "Unknown");
var p = new Person("John"); // LastName = "Unknown"
public record Car
{
public string Brand { get; init; } = "Unknown";
}
var c = new Car(); // Brand = "Unknown"
No, records are still reference types. You can use GetType()
, reflection, type checks, etc., just like with classes.
Yes, but you must define the Deconstruct
method manually. It works similarly to records once added.
Contact Sudipto Kumar Mukherjee – Microsoft Certified Trainer with 20+ years of experience in .NET, C#, ASP.NET Core.
Phone: +91-93318-97923
Location: Dum Dum, Kolkata
Email: supernova.software.solutions@gmail.com