r/csharp • u/PatrickSmacchia • Oct 12 '20
C#9 records: immutable classes
https://blog.ndepend.com/c9-records-immutable-classes/
118
Upvotes
r/csharp • u/PatrickSmacchia • Oct 12 '20
View all comments
Show parent comment
5
u/Ravek Oct 12 '20 edited Oct 12 '20
Much as I like Eric Lippert’s blog in general, this advice is really strange and only from the perspective of a language designer not actually a user.
For most types that are today structs, the difference between copy semantics is undetectable because they’re immutable. ints, floats, DateTime, etc. So why are they structs? Performance. You don’t want to heap allocate small immutable objects, you don’t want the extra memory footprint of heap allocated objects, nor do you want the extra indirection that references push on you.
So that’s immutable structs. Mutable structs are pretty rare – who wants a type with the potential for accidentally mutating a copy instead of the target? You can just use an immutable struct and create modified copies instead of actually mutating anything.
The answer is again performance. Replacing a whole struct object with a modified copy is slower than directly mutating it, especially for larger structs like vectors and matrices etc. The copy semantics are actually undesirable here, and out/ref are used a lot to avoid them.
I think it’s obvious that the reason structs even exist in the first place (compared to e.g. Java, which has only classes – and for performance reasons, some primitives) is for their performance benefits, and that the semantics are an unfortunate side effect of getting this performance – never the goal.
As further evidence, consider why ValueTuple and ValueTask exist rather than just sticking with classes. It’s all about performance. I can’t even think of a single example of a mutable struct which was clearly made a struct because of copy semantics being desirable. I wonder if Eric Lippert can.