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 cloninginitinit vs setinit 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
To keep every session productive and distraction-free, please follow these simple guidelines:
Following these guidelines helps you focus better and ensures I can deliver the best learning experience in every class.
I prefer to start with a short 10-minute free call so I can understand:
Why? Because course content, teaching pace, and fees all depend on your needs — there’s no “one-size-fits-all” pricing. Please leave your details below, and I’ll get back to you to arrange a convenient time for the call.
Note: Payment is made only after your first class, once you’re completely satisfied. However, fees paid after the first class are non-refundable. This helps maintain scheduling commitments and allows me to reserve your preferred time slot with full attention.