Search code examples
c#typesc#-10.0language-concepts

What Is The Purpose Of A Record Struct?


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?


Solution

  • The main benefits of using record struct are as follows:

    1. It allows you to simplify a struct definition to a single line
    2. It provides overloads for the == 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.
    3. It provides a more comprehensive 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.
    4. It can provide performance benefits over 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.

    Note

    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.

    Final Remark

    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.