What's the usecase for mutable records in C#9?
Asked Answered
W

1

22

C# 9 adds records, finally! I've been waiting forever for this, it's supergreat! But I'm wondering what the point of having a record with { get; set; } is? It seems like records should be immutable and use { get; init; } for all their properties. Maybe I'm just too used to working with immutable data, but I don't get the point of mutable records. It just seems like it increases the likelihood of bugs in the code. Am I missing a really obvious and useful usecase?

Waterlog answered 12/4, 2021 at 14:47 Comment(2)
To get the other features of records, such as positional deconstruct and value equality for otherwise simple types/DTOs?Aubine
The .NET runtime itself, at the core, does not support immutable types as first-class citizens, so pretending that records (which are just a new way of writing classes) provide "true" immutability (of which there are several flavors!) is of limited value. Records are a step in that direction, but not the final word, and trying to combine them with (enforced) immutability is a bridge too far. See also, see also.Prehuman
P
27

To start with: a record is just a quick, short notation to declare a class with a couple of useful features (a copy constructor + cloning + hashing + comparison/equality) automatically added for free. But the end result is still a class, like any other. It is syntactic sugar, with actually two flavours.

The extra-short positional syntax makes all properties init-only:

record Person(string FirstName, string LastName);

The less-short nominal syntax makes the developer responsible to specify set or init for each property:

record Person
{
    public string FirstName { get; set; }
    public string LastName { get; init; }
}

The reason behind offering both notations is that there is no 'one-size-fits-all'.

The more verbose nominal syntax allows to create a class with still very little code, with custom (im)mutability that the positional syntax does not offer, while still getting the copy constructor + cloning + hashing + comparison/equality for free.

Last but not least, both variants - just like classes - allow adding additional fields, properties and methods if you need them, example:

record Person(string FirstName, string LastName)
{
    public string FavColor;
    public string GetDisplayText()
    {
        return LastName + " " + FavColor;
    }
}
Perforate answered 12/4, 2021 at 15:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.