简体   繁体   中英

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

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
);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM