Immutability with Recods vs. Classes with auto-implemented get-only properties

Viewed 38

Is there any difference regarding immutablity when using classes with auto-implemented get-only properties versus a C# 9 record? I imagine compiler does backing fields(?) and magic under the hood to support the syntactic sugar, however say types below were data transfer objects, are they immutable once deserialized? Apart from the shorter syntax, is there any immutability enhancement of the record vs the class?

For instance

public class RgbColor 
{
    public RgbColor(int r, int g, int b) { /* do assign here ... */ }
    public int Red { get; }
    public int Green { get; }
    public int Blue { get; }
}

versus

public record RgbColor (
   int Red,
   int Green,
   int Blue
);
1 Answers

Docs:

You can create record types with immutable properties by using positional parameters or standard property syntax:

public record Person(string FirstName, string LastName);

And:

You can also create record types with mutable properties and fields:

public record Person
{
    public string FirstName { get; set; } = default!;
    public string LastName { get; set; } = default!;
};

This is equally mutable as your class.

Related