Records
suggest changeA record is a class or struct whose main job is to hold data. You write one line:
record Person(string First, string Last, int BirthYear);
and the compiler generates the rest:
- a constructor and
init-only propertiesFirst,Last,BirthYear - value equality:
Equals,GetHashCode,==and!=compare the property values, not references - a readable
ToString():Person { First = Ada, Last = Lovelace, BirthYear = 1815 } - support for
withexpressions, which make a copy with some properties changed - a
Deconstructmethod, sovar (first, last, year) = person;works (see Destructuring)
Versions:
- C# 9 (.NET 5):
record(a reference type, i.e. a class) - C# 10 (.NET 6):
record struct,readonly record struct, andrecord classas an explicit spelling ofrecord
The examples are .NET 10 / C# 14 file-based programs: save the code as app.cs and run it with dotnet run app.cs. All output comes from real runs.
Positional records
The parameter list after the name is the record's primary constructor. Each parameter becomes a public init-only property:
var a = new Person("Ada", "Lovelace", 1815);
var b = new Person("Ada", "Lovelace", 1815);
Console.WriteLine(a);
Console.WriteLine(a == b);
Console.WriteLine(a.Equals(b));
Console.WriteLine(ReferenceEquals(a, b));
Console.WriteLine(a.GetHashCode() == b.GetHashCode());
Console.WriteLine(a.First);
record Person(string First, string Last, int BirthYear);
Person { First = Ada, Last = Lovelace, BirthYear = 1815 }
True
True
False
True
Ada
a and b are two different objects (ReferenceEquals is false), but they hold the same data, so they're equal. A plain class would print Person, and a == b would be false.
The properties are init-only, so you can't change them after construction:
a.First = "Grace";
error CS8852: Init-only property or indexer 'Person.First' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.
Records aren't deeply immutable, though. If a property holds a List<T>, you can still add items to it. More on this below.
Nominal records
You don't have to use a primary constructor. A record with ordinary property declarations is called nominal, and you create it with an object initializer:
var p = new Product { Name = "Keyboard", Price = 49.99m };
Console.WriteLine(p);
record Product
{
public required string Name { get; init; }
public decimal Price { get; init; }
}
Product { Name = Keyboard, Price = 49.99 }
This style works well when a type has many properties, several of them optional, or when you want required (C# 11) to force callers to set some of them. You still get value equality, ToString and with. You don't get Deconstruct, because it is generated only from positional parameters.
You can mix the two styles. Extra properties in the body take part in equality and ToString like the positional ones. Public computed properties appear in ToString too:
var line = new Line(new Pt(0, 0), new Pt(3, 4)) { Label = "diagonal" };
Console.WriteLine(line);
Console.WriteLine(line.Length);
Console.WriteLine(line == new Line(new Pt(0, 0), new Pt(3, 4)));
record class Pt(int X, int Y);
record Line(Pt From, Pt To)
{
public string? Label { get; init; }
public double Length => Math.Sqrt(Math.Pow(To.X - From.X, 2) + Math.Pow(To.Y - From.Y, 2));
}
Line { From = Pt { X = 0, Y = 0 }, To = Pt { X = 3, Y = 4 }, Label = diagonal, Length = 5 }
5
False
The last line is False because Label differs ("diagonal" vs null). Nested records compare by value, because Pt has its own value equality.
What the compiler generates
Reflection shows the members of record Point(int X, int Y);:
using System.Reflection;
const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
foreach (var m in typeof(Point).GetMembers(flags).OrderBy(m => m.Name))
{
if (m is MethodInfo { IsSpecialName: true } mi && !mi.Name.StartsWith("op_")) continue;
Console.WriteLine($"{m.MemberType,-12} {m}");
}
record Point(int X, int Y);
Constructor Void .ctor(Int32, Int32)
Constructor Void .ctor(Point)
Method Point <Clone>$()
Field Int32 <X>k__BackingField
Field Int32 <Y>k__BackingField
Method Void Deconstruct(Int32 ByRef, Int32 ByRef)
Property System.Type EqualityContract
Method Boolean Equals(System.Object)
Method Boolean Equals(Point)
Method Int32 GetHashCode()
Method Boolean op_Equality(Point, Point)
Method Boolean op_Inequality(Point, Point)
Method Boolean PrintMembers(System.Text.StringBuilder)
Method System.String ToString()
Property Int32 X
Property Int32 Y
.ctor(Point)is a protected copy constructor and<Clone>$calls it. Together they implementwith.Equals(Point)comparesEqualityContract(the runtime type) and then every field usingEqualityComparer<T>.Default.GetHashCodecombines the same fields.ToStringwrites the type name and callsPrintMembers, which writesName = valuefor every public field and property.- The record also implements
IEquatable<Point>.
Writing this by hand for a class takes about 50 lines, and it has to be updated every time you add a property (see Equals and GetHashCode). With a record the compiler keeps it in sync.
with expressions: non-destructive mutation
Because records are meant to be immutable, you "change" one by making a modified copy. A with expression copies the record and then runs an object initializer on the copy:
var order = new Order(1001, "Ada", 120.00m, "pending");
var paid = order with { Status = "paid" };
var bigger = paid with { Total = paid.Total * 2, Status = "paid (x2)" };
var copy = order with { };
Console.WriteLine(order);
Console.WriteLine(paid);
Console.WriteLine(bigger);
Console.WriteLine($"copy == order: {copy == order}, same object: {ReferenceEquals(copy, order)}");
record Order(int Id, string Customer, decimal Total, string Status);
Order { Id = 1001, Customer = Ada, Total = 120.00, Status = pending }
Order { Id = 1001, Customer = Ada, Total = 120.00, Status = paid }
Order { Id = 1001, Customer = Ada, Total = 240.00, Status = paid (x2) }
copy == order: True, same object: False
order is unchanged. with { } makes an exact copy.
The copy is shallow. Reference-type properties are copied as references, so both records point to the same list:
var tags = new List<string> { "new" };
var a = new Item("pen", tags);
var b = a with { Name = "pencil" };
b.Tags.Add("sale");
Console.WriteLine(string.Join(",", a.Tags));
Console.WriteLine(ReferenceEquals(a.Tags, b.Tags));
record Item(string Name, List<string> Tags);
new,sale
True
If you need a record that is really immutable, use immutable property types: string, other records, ImmutableArray<T> / ImmutableList<T> (see Immutable collections) or IReadOnlyList<T> that nobody casts back. with also works on structs and anonymous types since C# 10.
Equality gotcha: collections compare by reference
The generated Equals compares each property with its own Equals. Arrays and List<T> don't override Equals, so two records with identical arrays are not equal:
var a = new Product("Keyboard", ["usb", "wireless"]);
var b = new Product("Keyboard", ["usb", "wireless"]);
Console.WriteLine($"Product equal: {a == b}");
record Product(string Name, string[] Tags);
Product equal: False
ToString isn't helpful for them either: it prints Tags = System.String[]. You can replace the generated members. If you write Equals(T), you must also write GetHashCode (the compiler warns otherwise). In a non-sealed record Equals(T) must be virtual:
var c = new Product2("Keyboard", ["usb", "wireless"]);
var d = new Product2("Keyboard", ["usb", "wireless"]);
Console.WriteLine($"Product2 equal: {c == d}");
Console.WriteLine($"same hash: {c.GetHashCode() == d.GetHashCode()}");
Console.WriteLine(c);
record Product2(string Name, string[] Tags)
{
public virtual bool Equals(Product2? other) =>
other is not null &&
EqualityContract == other.EqualityContract &&
Name == other.Name &&
Tags.SequenceEqual(other.Tags);
public override int GetHashCode()
{
var h = new HashCode();
h.Add(Name);
foreach (var t in Tags) h.Add(t);
return h.ToHashCode();
}
public override string ToString() =>
$"Product2 {{ Name = {Name}, Tags = [{string.Join(", ", Tags)}] }}";
}
Product2 equal: True
same hash: True
Product2 { Name = Keyboard, Tags = [usb, wireless] }
==, != and Equals(object) call your Equals(Product2?), so you only write it once. If you do this for many records, consider making the property an ImmutableArray<T> wrapper type with value equality instead.
Customizing generated members
Any member you declare yourself replaces the generated one. Common customizations:
- Validate a positional parameter by declaring the property yourself and initializing it from the parameter.
- Hide sensitive data from
ToStringby writingPrintMembers. - Add computed properties, methods and static factories to the body as in any class.
var u = new User("ada@example.com", "s3cret!");
Console.WriteLine(u);
Console.WriteLine(u.Domain);
Try(() => new User("ada.example.com", "x"));
Try(() => u with { Email = "not-an-email" });
static void Try(Func<User> f)
{
try { Console.WriteLine(f()); }
catch (ArgumentException ex) { Console.WriteLine($"error: {ex.Message}"); }
}
record User(string Email, string Password)
{
// replaces the generated Email property
public string Email { get; init => field = Validate(value); } = Validate(Email);
public string Domain => Email[(Email.IndexOf('@') + 1)..];
// keep the password out of ToString
protected virtual bool PrintMembers(System.Text.StringBuilder sb)
{
sb.Append($"Email = {Email}, Password = ***");
return true;
}
static string Validate(string email) =>
email.Contains('@') ? email : throw new ArgumentException($"invalid email '{email}'");
}
User { Email = ada@example.com, Password = *** }
example.com
error: invalid email 'ada.example.com'
error: invalid email 'not-an-email'
Validation has to happen in two places:
- The initializer
= Validate(Email)runs in the constructor. withdoesn't call the constructor. It copies the fields and then calls theinitaccessor. Soinitvalidates too. It uses the C# 14fieldkeyword to get at the backing field without declaring one.
If you validate only in the initializer, with bypasses it:
var u = new User("ada@example.com");
Console.WriteLine(u with { Email = "not-an-email" });
record User(string Email)
{
public string Email { get; init; } = Email.Contains('@')
? Email
: throw new ArgumentException($"invalid email '{Email}'");
}
User { Email = not-an-email }
PrintMembers must be protected virtual in a non-sealed record and private in a sealed one. You can also override ToString directly, as Product2 does above. Mark it sealed override if derived records shouldn't change it.
To put an attribute on the generated property instead of the constructor parameter, use the property: target. Records work with System.Text.Json, which calls the primary constructor during deserialization:
using System.Text.Json;
using System.Text.Json.Serialization;
var e = new Event(7, "Deploy", new DateOnly(2026, 10, 18), "eu-west");
string json = JsonSerializer.Serialize(e, AppJson.Default.Event);
Console.WriteLine(json);
var back = JsonSerializer.Deserialize(json, AppJson.Default.Event)!;
Console.WriteLine(back);
Console.WriteLine(back == e);
record Event(
int Id,
string Title,
[property: JsonPropertyName("on")] DateOnly Date,
string Region);
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]
[JsonSerializable(typeof(Event))]
partial class AppJson : JsonSerializerContext;
{"id":7,"title":"Deploy","on":"2026-10-18","region":"eu-west"}
Event { Id = 7, Title = Deploy, Date = 10/18/2026, Region = eu-west }
True
The example uses a source-generated JsonSerializerContext because file-based apps have Native AOT enabled by default, which turns off reflection-based JSON serialization. The date in ToString depends on the current culture.
Inheritance
A record can inherit from another record (never from a class, and a class can't inherit from a record). The derived record passes the positional parameters on to the base record:
Shape s1 = new Circle("red", 2.0);
Shape s2 = new Square("red", 2.0);
Console.WriteLine(s1);
Console.WriteLine(s2);
// same Color, but different runtime types: not equal
Shape plain = new Shape("red");
Console.WriteLine($"Shape == Circle: {plain == s1}");
Console.WriteLine($"Circle == Circle: {s1 == new Circle("red", 2.0)}");
// 'with' on a Shape variable keeps the runtime type and the derived fields
Shape blue = s1 with { Color = "blue" };
Console.WriteLine(blue);
Console.WriteLine(blue.GetType().Name);
Console.WriteLine(Area(s1));
Console.WriteLine(Area(s2));
static double Area(Shape s) => s switch
{
Circle c => Math.Round(Math.PI * c.Radius * c.Radius, 2),
Square sq => sq.Side * sq.Side,
_ => 0,
};
record Shape(string Color);
record Circle(string Color, double Radius) : Shape(Color);
sealed record Square(string Color, double Side) : Shape(Color);
Circle { Color = red, Radius = 2 }
Square { Color = red, Side = 2 }
Shape == Circle: False
Circle == Circle: True
Circle { Color = blue, Radius = 2 }
Circle
12.57
4
Three things work here that are easy to get wrong in hand-written classes:
- Equality is symmetric across a hierarchy.
EqualschecksEqualityContract(the runtime type) first, so aShapeis never equal to aCircle, however you compare them. ToStringis virtual, so it prints the derived type and all of its properties, even through aShapevariable.withis virtual. It calls the virtual<Clone>$method, so the copy is aCirclewith itsRadiuskept.
Records and pattern matching make a natural pair for closed sets of cases like this, sometimes called algebraic data types.
Trying to mix records and classes fails to compile:
record class A(int X);
class B(int X) : A(X);
record C(int Y) : Exception;
error CS8864: Records may only inherit from object or another record
error CS8865: Only records may inherit from records.
record struct and readonly record struct
record struct (C# 10) gives a struct the same generated members. It is a value type: it lives inline, it's copied on assignment (see Structs), and default gives you all-zero fields.
One difference trips people up: the positional properties of a record struct are mutable (get; set;). Add readonly to get init-only properties like a record class:
var p1 = new Point(1, 2);
var p2 = p1; // copied, like any struct
p2.X = 10; // record struct properties are mutable
Console.WriteLine($"{p1} {p2}");
Console.WriteLine(p1 == new Point(1, 2));
var m = new Money(9.99m, "EUR");
var m2 = m with { Amount = 19.99m };
Console.WriteLine($"{m} {m2}");
Point def = default;
Console.WriteLine(def);
var (amount, currency) = m2;
Console.WriteLine($"{amount} {currency}");
record struct Point(int X, int Y);
readonly record struct Money(decimal Amount, string Currency);
Point { X = 1, Y = 2 } Point { X = 10, Y = 2 }
True
Money { Amount = 9.99, Currency = EUR } Money { Amount = 19.99, Currency = EUR }
Point { X = 0, Y = 0 }
19.99 EUR
Assigning to Money.Amount gives the same CS8852 error as for a record class.
Record structs can't inherit (no struct can), so there is no EqualityContract.
A record struct is also faster than a plain struct used as a key. A struct that doesn't override Equals and GetHashCode gets ValueType's default versions, which can use reflection. Worse, the default GetHashCode may hash only the first field. A record struct gets fast, generated, field-by-field versions:
using System.Diagnostics;
const int N = 100_000;
var sw = Stopwatch.StartNew();
var plain = new HashSet<PlainKey>();
for (int i = 0; i < N; i++) plain.Add(new PlainKey($"host{i % 1000}", i));
Console.WriteLine($"struct: {sw.ElapsedMilliseconds,5} ms");
sw.Restart();
var rec = new HashSet<RecordKey>();
for (int i = 0; i < N; i++) rec.Add(new RecordKey($"host{i % 1000}", i));
Console.WriteLine($"record struct: {sw.ElapsedMilliseconds,5} ms");
// no Equals/GetHashCode override: falls back to ValueType's versions
struct PlainKey(string host, int id)
{
public string Host = host;
public int Id = id;
}
readonly record struct RecordKey(string Host, int Id);
struct: 937 ms
record struct: 17 ms
That's dotnet run -c Release app.cs. The plain struct's hash code depends only on Host, which has 1,000 distinct values, so the HashSet is full of collisions. With 1,000,000 items the plain struct took 45 seconds and the record struct 0.2 seconds. Any time you use a struct as a dictionary key or in a set, make it a readonly record struct or implement IEquatable<T> yourself.
Records as composite keys
Value equality makes records ideal dictionary keys. You don't need a "host|path" string or a tuple with unnamed fields:
var visits = new Dictionary<PageKey, int>();
foreach (var (host, path) in new[] { ("a.com", "/"), ("a.com", "/about"), ("a.com", "/") })
{
var key = new PageKey(host, path);
visits[key] = visits.GetValueOrDefault(key) + 1;
}
foreach (var (k, n) in visits) Console.WriteLine($"{k}: {n}");
readonly record struct PageKey(string Host, string Path);
PageKey { Host = a.com, Path = / }: 2
PageKey { Host = a.com, Path = /about }: 1
Don't use a record whose properties can change (a record struct, or a record with a mutable list) as a key. If its hash code changes while it's in a dictionary, you can't find the entry anymore.
When to use a record
| Use | When |
|---|---|
record (class) |
DTOs, API requests and responses, messages, events, configuration snapshots, results of queries; anything whose identity is its data. Also hierarchies of cases matched with switch. |
readonly record struct |
Small values (a few fields, roughly 16 bytes or less): money, coordinates, ids, composite keys. No heap allocation. |
record struct |
Rarely. When you want a mutable value type with generated equality and ToString. |
class |
Objects with identity and behavior: services, entities tracked by an ORM (EF Core tracks entities by reference, and value equality confuses it), anything with mutable state or resources (IDisposable). |
struct |
Low-level, performance-sensitive code where you control every member. Implement IEquatable<T> yourself. |
tuple (int, string) |
Short-lived values inside one method, or a private helper's return value (see Tuples). Once it crosses an API boundary, give it a name with a record. |
Other things to know:
- Records don't implement
IComparable<T>, soSort()andOrderBy(x => x)on them throw. Sort by a property, or implementIComparable<T>yourself. GetHashCodeis computed every time you call it, from all the fields. For a big record used heavily as a key, cache it or key on a smaller record.- Records can be generic (
record Result<T>(T Value, string? Error);), implement interfaces, and have static members, like any class or struct. - Classes and structs can also have primary constructors since C# 12 (
class Service(ILogger log)), but those parameters are only captured: no properties, equality,ToStringorDeconstructare generated.
See also Immutability for why immutable data types are easier to reason about.