Record structs
record struct
record struct is a struct with the record parts: a constructor, a property per parameter, value equality and a generated ToString. The difference from a record class is the same difference as between a struct and a class: a value is copied, it is never null, and it costs no heap allocation.
var first = new Point(1, 2);
var second = first with { Y = 5 };
Console.WriteLine(first);
Console.WriteLine(second);
Console.WriteLine($"equal {first == new Point(1, 2)}");
Console.WriteLine($"copy equal {first == second}");
record struct Point(int X, int Y);
dotnet run
Point { X = 1, Y = 2 }
Point { X = 1, Y = 5 }
equal True
copy equal False
The generated text has the same shape as the class record version, and with works too. The two points stay two values: changing the copy does not touch the original, which the first two lines prove.
readonly record struct
By default a record struct has settable properties, because a struct that lives on the stack can be written where it stands. Add readonly to get the immutable value, which is the shape that behaves like a record class:
var first = new Money(10m, "EUR");
var second = first with { Amount = 12m };
Console.WriteLine($"{first.Amount} {first.Currency}");
Console.WriteLine($"{second.Amount} {second.Currency}");
Console.WriteLine($"equal {first == new Money(10m, "EUR")}");
readonly record struct Money(decimal Amount, string Currency);
dotnet run
10 EUR
12 EUR
equal True
The two money values compare equal by amount and currency, and the copy changed one of them. A readonly record struct is the natural type for an amount with a unit, a range with two ends, or any small value that is read far more often than it is built.
A mutable record struct
A record struct without readonly may be changed in place, which is useful in a hot loop where a copy per change would be the cost. The program prints the value and its size in memory:
var point = new Point(1, 2);
point.X = 9;
Console.WriteLine(point);
Console.WriteLine($"size {System.Runtime.InteropServices.Marshal.SizeOf<Point>()}");
record struct Point(int X, int Y);
dotnet run
Point { X = 9, Y = 2 }
size 8
Eight bytes for two integers: the value is its fields and nothing else, no object header and no reference. A class with two integers costs the header, the two fields and the reference to it, and one allocation; the lesson on struct against class measures that difference.
No inheritance, and the error
A record struct may implement an interface and may not inherit from another record struct: value types have no inheritance in the CLR. Writing the colon anyway gives a diagnostic that names the type as an interface list:
var point = new Point(1, 2);
var other = new Point(1, 2);
Console.WriteLine(point);
Console.WriteLine($"default {default(Point)}");
Console.WriteLine($"equal {point.Equals(other)}");
record struct Point(int X, int Y);
record struct Named(string Name) : Point;
dotnet build
Program.cs(10,36): error CS0527: Type 'Point' in interface list is not an interface
Build FAILED.
Program.cs(10,36): error CS0527: Type 'Point' in interface list is not an interface
0 Warning(s)
1 Error(s)
Time Elapsed 00:00:04.56
The compiler read the colon as the start of an interface list, because that is the only thing a struct can put there. The three lines above the failing declaration would have printed Point { X = 1, Y = 2 }, default Point { X = 0, Y = 0 } and equal True; the build stops at the error, so they are described here rather than shown as output.
When a value record is right
- A small value with value equality, used in collections and compared often: a coordinate, a range, a money amount.
- A value that is created in a loop by the million, where one allocation per item would be the cost: a record struct is the same data without the allocation.
- Not where the record is large or grows: copying a fifty-field struct on every with costs more than copying a reference.
- Not where null means something: a struct has no null, so a missing value needs Nullable<T> or a record class.
Exercises
- Change record struct Point to record class Point and rerun the first program. Which lines change?
- Try to set first.Amount = 20m on the readonly struct and read the error.
- Put a record struct and a class with the same fields into an array of ten thousand and compare GC.GetTotalMemory before and after.
- Give Point a method that returns a new point moved by a delta, and use it in a loop.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a record struct add to a struct?
Answer
A constructor, properties, value equality and a generated ToString
The record syntax generates the data-type members; the value semantics stay those of a struct.
-
How do you make a record struct immutable?
Answer
Declare it readonly record struct
Without readonly its properties are settable, unlike a record class.
-
What does this program print?
var a = new P(1); var b = a; b.N = 5; Console.WriteLine(a.N + b.N); record struct P(int N);Answer
6
b is a copy of the value, so a.N stays 1 and the sum is 6.
-
Can a record struct inherit from another record struct?
Answer
No, a struct has no base type except interfaces
CS0527 reports the type in the interface list, because that is the only list a struct has.
-
What is
default(Point)for a record struct?Answer
A value with every field at zero
A value type always has a zeroed default value.
-
What does this program print?
var m = new M(2m, "EUR"); var n = m with { Amount = 3m }; Console.WriteLine($"{m.Amount}/{n.Amount}"); readonly record struct M(decimal Amount, string Currency);Answer
2/3
with copies the value and replaces one property, so the original keeps 2.
-
Why is a record struct cheaper than a record class for a million items?
Answer
It lives inside the array with no object per item
An array of structs holds the values themselves, so there is one allocation for the array.
-
What does Marshal.SizeOf<Point>() report for two int fields?
Answer
8 bytes
Two 32-bit integers are eight bytes, with no object header.
-
Which value cannot a record struct property hold?
Answer
null, unless it is a nullable type
A struct is never null; a missing value needs Nullable<T> or a class.
-
What is the difference between record struct and readonly record struct?
Answer
The second one has no settable properties
readonly makes every property init-only, so a change must produce a copy.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev