C# 9 added the record
type, which is a new reference type that uses value-based equality.
C# 10 introduced the record struct
syntax to define a value type with similar properties to record
(https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record).
It seems unusual to create a value type version of a type that was created to be a reference type that also has value-based equality - that would surely remove most of the benefit of using the type.
Why would you ever want to declare a record struct
?
Is there something more that I am missing?
The main benefits of using record struct
are as follows:
struct
definition to a single line==
and !=
operators, so these can be used for comparisons with no extra code to define the operator overloads. With struct
, you can only do comparisons using the Equals()
method by default.ToString()
method than struct
. The record struct
ToString()
method will produce the record struct
name, the names of its properties and their values. The struct
default ToString()
method only produces the struct
name.struct
In some ways, record
is similar to a value tuples which provide default operator overloads and have a ToString()
method that is closer to record struct
(value tuples' ToString()
method produces the values of all of their properties).
However, value tuples are only used on the fly, whereas record struct
can be used to define type that will be repeatedly used.
record
/ record class
is immutable by default but record struct
is not, so if you want an immutable record struct
, you must use readonly record struct
.
Considering the benefits of using record struct
over struct
, it's probably best to always prefer record struct
unless there is some very specific reason not to.
It seems that record struct
is an enhancement of struct
, leaving the old type so that existing behaviour/functionality of struct
is not removed.