C# Structs & Records
Classes are not the only way to define your own types. C# also has structs — lightweight value types — and records, which are designed for data whose identity is defined by its values. Choosing well between them makes code both clearer and faster.
Structs are value types
A struct looks much like a class, but a struct variable contains the data itself, not a reference to it. Assigning a struct copies all of its fields.
using System;
PointStruct s1 = new PointStruct(1, 2);
PointStruct s2 = s1; // full copy
s2.X = 100;
Console.WriteLine(quot;struct: s1.X={s1.X}, s2.X={s2.X}");
PointClass c1 = new PointClass(1, 2);
PointClass c2 = c1; // copy of the reference
c2.X = 100;
Console.WriteLine(quot;class: c1.X={c1.X}, c2.X={c2.X}");
struct PointStruct
{
public int X;
public int Y;
public PointStruct(int x, int y) { X = x; Y = y; }
}
class PointClass
{
public int X;
public int Y;
public PointClass(int x, int y) { X = x; Y = y; }
}struct: s1.X=1, s2.X=100
class: c1.X=100, c2.X=100
Many built-in types are structs: int, double, bool, char, decimal, DateTime, TimeSpan and Guid.
When to use a struct
Structs avoid a heap allocation, which matters when you create millions of small values. Microsoft's guidelines suggest a struct when the type:
- represents a single small value (like a point, a colour or a money amount),
- is small — roughly 16 bytes or less,
- is ideally immutable,
- will not need to be boxed (converted to
object) frequently.
Marking a struct readonly makes the compiler enforce immutability:
using System;
var a = new Vector2(3, 4);
var b = new Vector2(1, 2);
Console.WriteLine(a + b);
Console.WriteLine(a.Length);
Console.WriteLine(a == new Vector2(3, 4));
readonly struct Vector2
{
public double X { get; }
public double Y { get; }
public Vector2(double x, double y) { X = x; Y = y; }
public double Length => Math.Sqrt(X * X + Y * Y);
public static Vector2 operator +(Vector2 p, Vector2 q) => new Vector2(p.X + q.X, p.Y + q.Y);
public static bool operator ==(Vector2 p, Vector2 q) => p.X == q.X && p.Y == q.Y;
public static bool operator !=(Vector2 p, Vector2 q) => !(p == q);
public override bool Equals(object obj) => obj is Vector2 v && this == v;
public override int GetHashCode() => HashCode.Combine(X, Y);
public override string ToString() => quot;({X}, {Y})";
}(4, 6)
5
True
That is a lot of boilerplate for equality — which is exactly what records remove.
Records
A record is a type whose compiler-generated members treat it as data: two records are equal when all their values are equal, ToString prints every property, and copies with changes are one expression away. The shortest form is the positional record:
using System;
var p1 = new Person("Ada", "Lovelace", 1815);
var p2 = new Person("Ada", "Lovelace", 1815);
Console.WriteLine(p1);
Console.WriteLine(p1 == p2); // value equality
Console.WriteLine(ReferenceEquals(p1, p2)); // still two objects
var older = p1 with { BirthYear = 1800 }; // non-destructive copy
Console.WriteLine(older);
var (first, last, year) = p1; // deconstruction
Console.WriteLine(quot;{last}, {first} ({year})");
record Person(string FirstName, string LastName, int BirthYear);Person { FirstName = Ada, LastName = Lovelace, BirthYear = 1815 }
True
False
Person { FirstName = Ada, LastName = Lovelace, BirthYear = 1800 }
Lovelace, Ada (1815)
From one line, the compiler generated: a constructor, init-only properties, Equals/GetHashCode/==, a readable ToString, Deconstruct, and support for with expressions.
Records can have members too
Records are classes (reference types) by default; record struct makes a value-type record. Either can contain extra properties and methods, and records support inheritance:
using System;
var line = new OrderLine("Mug", 2, 7.5m);
Console.WriteLine(line.Total);
Console.WriteLine(line with { Quantity = 5 });
var p = new Point(2, 3);
var q = p with { Y = 10 };
Console.WriteLine(quot;{p} {q} {p.Equals(new Point(2, 3))}");
record OrderLine(string Product, int Quantity, decimal UnitPrice)
{
public decimal Total => Quantity * UnitPrice;
}
record struct Point(int X, int Y);15.0
OrderLine { Product = Mug, Quantity = 5, UnitPrice = 7.5, Total = 37.5 }
Point { X = 2, Y = 3 } Point { X = 2, Y = 10 } True
Class, struct or record?
class |
struct |
record (class) |
record struct |
|
|---|---|---|---|---|
| Kind | Reference | Value | Reference | Value |
| Assignment copies | Reference | Data | Reference | Data |
== compares |
Identity | Not defined (unless you add it) | Values | Values |
Readable ToString |
No | No | Yes | Yes |
with expressions |
No | Yes | Yes | Yes |
| Inheritance | Yes | No | Yes (records only) | No |
| Typical use | Entities with behaviour and identity | Tiny values, performance | Immutable data, DTOs, messages | Tiny immutable values |
Tip: Use a record for data that you pass around and compare (API responses, configuration, events). Use a class when the object has an identity that persists while its data changes — a
Customeris still the same customer after changing their address.
Test yourself
What does assigning one struct variable to another do?
- Copies the reference
- Copies all the data
- Moves the data
- Shares the same memory
Two record instances have identical property values. What does r1 == r2 return?
- False, they are different objects
- True, records use value equality
- It does not compile
- It depends on GetHashCode
What does p with { Age = 30 } do for a record p?
- Changes p's Age to 30
- Creates a copy of p with Age set to 30
- Compares Age with 30
- Deletes the Age property