Microsoft sure fucked up this one. Back in good old C++, you could decide whether you need value semantics or reference semantics right where you needed it: When the class or structure was used. In .NET, your entire data type is a so called “value type” or a “reference type”.
I don’t know what the guys were smoking when they came up with this “simplification”, but in the end, it doesn’t have a single advantage and causes loads of trouble. For example in object comparison: In C++, you had to override a single operator and you absolutely knew that this operator had to compare the values of the instances, not the object identity. That was clear, precise and implementation took only 5 lines at most.
Now .NET has “improved” upon this: You have object.Equals() and operator == and operator !=. To barely avoid code duplication is hard enough already. But then one still doesn’t know, as the user of an object, whether the object’s comparison operators will perform an object identity comparison or a value comparison, because its implementors are free to decide that on a case-by-case basis. All in all that takes you a good 20 lines of code on average - just to provide safe object comparison while you co-worker will still not know what kind of comparison is done.
And what happens if you assign one variable to another is no longer as clear and simple as it was in C++. Depending on whether you’ve got a value type or a reference type, the assignment might create a deep copy of the object or just reuse the reference. You can only be sure that a deep copy is made by explicitely calling the copy constructor — if the implementor has provided one. Again, there’s ICloneable to make it even worse. That interface is something like a brain misfire because it works for simple classes but will become utterly useless once you try it on derived classes.
Oh, and before I forget, there’s also IComparable, the ‘ref’ keyword which gives limited reference semantics to value types and from .NET 2.0 onwards also the generic version of IComparable…
Recent Comments