1.2 — struct vs class vs record vs record struct¶
← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.1 Value vs reference types · Next: 1.3 Strings
Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
- There are two separate questions. First: is it copied or shared? (
struct= copied,class= shared). Second: how does==compare it? (record= by content, normal class = by address). classis your default. Only usestructwhen the thing is small, never changes, and does not live long.- A
recordis not a new kind of type. It is just a class where the compiler writes some extra code for you.
The concept¶
C# gives you four ways to declare a type. It sounds like a lot, but it is really just two yes/no questions combined.
Question 1: When I assign this to another variable, is the data copied or shared?
- Copied → struct
- Shared → class
Question 2: When I use ==, does it compare the contents or check if they are the same object?
- Compares contents → add the word record
- Checks if same object → do not add record
Put those together and you get four combinations:
| Shared (reference) | Copied (value) | |
|---|---|---|
== checks same object |
class |
— |
== compares contents |
record |
record struct |
| (struct, compares contents but slowly) | — | struct |
That last row needs a note. A plain struct does compare by contents, but it does so in
a slow way behind the scenes (it uses reflection, which means inspecting the type at
runtime). A record struct gets fast comparison code written by the compiler instead.
How it works¶
class — the default¶
This is a reference type. Two variables can point to the same object. == checks whether
they are the same object, not whether they look the same.
Use a class unless you have a specific reason not to. The advice is not "use structs for speed" — it is "use classes, and switch only when you can explain why."
struct — copied every time¶
A struct is a value type. Every time you assign it, pass it to a method, or return it, the whole thing gets copied.
It cannot inherit from another struct or class (though it can implement interfaces), and
it cannot be null unless you write it as Point?.
Microsoft's rule of thumb for when a struct is a good idea — all four should be true:
- It represents one single value (like a point, or an amount of money).
- It is small — around 16 bytes or less.
- It never changes after it is created.
- It will not get boxed often. (Boxing means being wrapped in an object — see 1.1.)
If any one of these is false, use a class.
record — a class with free extra code¶
When you write record, the compiler automatically writes several things for you that you
would otherwise type by hand:
Equals,GetHashCode, and==that compare the property values- a
ToStringthat prints out the properties (very useful when debugging) - a
Deconstructmethod, so you can split it into separate variables - support for
with, which makes a copy with one property changed
public record Person(string FirstName, string LastName);
var a = new Person("Ada", "Lovelace");
var b = new Person("Ada", "Lovelace");
a == b;
// TRUE. These are two different objects in memory,
// but a record compares the values inside them.
// A normal class would say false here.
var c = a with { LastName = "Byron" };
// Creates a NEW Person. FirstName is copied from 'a' automatically.
// 'a' itself is not changed at all.
Console.WriteLine(a); // Person { FirstName = Ada, LastName = Lovelace }
Console.WriteLine(c); // Person { FirstName = Ada, LastName = Byron }
Notice the ToString output. You get that for free — with a normal class you would just
see the type name.
When you write a record in that short form (with the properties in brackets after the
name), those properties are init-only. That means you can set them when creating the
object and never again. So records are immutable by default. See 1.6.
record struct — copied and compares by content¶
This gives you three good things at once:
- no heap allocation, because it is a struct
- content-based comparison, because it is a record
- cannot be changed, because of
readonly
That combination is a great fit for small domain values like money, coordinates, or measurements.
The readonly keyword here matters for speed too. When the compiler knows a struct can
never change, it does not need to make protective copies of it when passing it around.
Code¶
Here is how each one looks in real code, and why:
// CLASS — an entity. It has an identity, it changes over time,
// and it has behaviour (methods that do things).
public class Order
{
public Guid Id { get; init; }
public List<OrderLine> Lines { get; } = [];
public void AddLine(OrderLine line) => Lines.Add(line);
}
// RECORD — a data carrier. It just holds values and gets passed around.
// Perfect for API request/response models, messages, query results.
public record CustomerDto(Guid Id, string Name, string Email);
// READONLY RECORD STRUCT — a small value that never changes.
// No heap allocation, compares by content.
public readonly record struct Point(double X, double Y);
// PLAIN STRUCT — rare. Only when you need exact control over
// memory layout, usually for talking to non-.NET code.
public struct RawHeader
{
public int Length;
public int Flags;
}
The mutable struct trap¶
This is worth understanding because it shows why the advice is "make structs readonly".
Now watch what happens with two almost identical lines:
var list = new List<Counter> { new Counter() };
list[0].Increment();
// This does NOT COMPILE.
// A List's indexer RETURNS A COPY of the struct.
// C# stops you, because incrementing a copy would do nothing useful.
var array = new Counter[1];
array[0].Increment();
// This DOES compile, and it DOES work.
// An array indexer gives you direct access to the element itself,
// not a copy. So the increment sticks.
Same-looking code, two different outcomes. The compiler saved you in one case and not the
other. This is exactly the kind of surprise that makes people say "just make structs
readonly" — if the struct cannot change at all, this whole problem disappears.
Interview questions¶
Q: When would you use a struct instead of a class?
When the type is one small value that never changes and does not live very long —
something like a point, a money amount, or a date range. The benefit is that you avoid
allocating memory on the heap, which means less work for the garbage collector. But it is
easy to get wrong. A big struct is slow because it gets copied every single time you pass
it around. And if it ends up boxed — wrapped in an object — you have paid for an
allocation anyway and gained nothing. So the default should stay class.
Q: What does record actually give you over a class?
The compiler writes four things for you: equality that compares the values inside,
a readable ToString, deconstruction, and the with expression for making a modified
copy. Underneath it is still a class — same reference behaviour, same heap allocation.
What changes is how equality works and the fact that properties are init-only by default.
It is the right choice for anything you would describe as "a bag of data": DTOs, API
models, messages, events.
Q: Are records immutable?
The short form with properties in brackets is, because the compiler makes those properties
init-only. But you can also write a record with normal settable properties, and then it is
fully mutable. So record does not mean "immutable" — it means "value equality plus with
support". Immutability comes from init, which the short form happens to use.
Q: What is the problem with a mutable struct?
You can end up changing a copy without realising it, because structs get copied whenever
they are passed around or returned from a property or an indexer. The clearest example is
that calling a method that changes a struct through a List indexer will not even
compile, but doing exactly the same thing through an array does compile and does work —
because an array gives you the element itself while a list gives you a copy. Making the
struct readonly removes the entire category of bug.
Traps ⚠️¶
- "Structs are faster than classes." Only for small, short-lived values. A big struct gets copied on every assignment and every method call, which can easily be slower than one heap allocation.
- Boxing cancels the benefit. Putting a struct in a non-generic collection, or using it through a non-generic interface, allocates on the heap anyway.
recorddoes not mean immutable. It means value equality pluswith.- A plain
struct's built-inEqualsis slow. It inspects the type at runtime. Either write your own or userecord struct. - Record equality includes every field — including collections, compared by address. So two records that both contain a list with the same items will be reported as not equal, because the two lists are different objects. Records are best for simple data.
Related¶
- 1.1 Value vs reference types — the idea underneath all of this
- 1.6
initandrequired— how record immutability works - 1.25
Span<T>— where structs really pay off - 10.11 DTOs — records as API models
- 22.8 DDD value objects —
readonly record structin domain design