3 ms·
As great as structs in C# for performance reasons are: They also provide several new ways to shoot yourself in the foot if you don't understand their behavior t
by Matthias247 9y ago
As great as structs in C# for performance reasons are: They also provide several new ways to shoot yourself in the foot if you don't understand their behavior to 100%.
One example that I run many years ago was having a struct Foo { int x; } which was nested inside a List<Foo> myList. Trying to mutate one list element with syntax like myList[0].x = 27 silently failed, because the indexer of the list returns a copy of Foo and you mutate that inside of writing it back. Nowadays its a compiler error, but back then it wasn't. The workaround is something like "Foo f = myList[0]; f.x = 27; myList[0] = f;". Which is quite weird if you are coming from C++. From a C# point of view it's actually obvious, since you can't pass around references and pointers to structs inside of other things - and if you also add this functionality, you get lots of the complexity from C++ back (references to structs, functions/properties that return references, questions around reference lifetimes, etc.). Without having also reference semantics for structs, structs also can't achieve the kind of performance which "value types" in C++ have, since they sometimes need to be copied fully.
Another nice gotcha is the surprising behavior of readonly structs, which e.g. is documented here: https://bytes.com/topic/c-sharp/answers/261922-readonly-behavior-structs https://bytes.com/topic/c-sharp/answers/261922-readonly-beha...
For those reasons I think it's quite fair that Java and other languages did not immediately jump onto the value types train. I think introducing them carefully, and trading off the performance gains against the amount of new complexity in the language is fine.
- pjmlp 9y agoWhen Java was introduced we already had plenty of GC enabled languages with value types. Eiffel, Oberon, Modula-2+, Modula-3, VB, are just a few examples. Hence why I always saw as lost opportunity not to provide them in first place.