I’m working on a project that uses significant amounts of C# and thus I’m refreshing my knowledge of the language. I’ve just noticed that C# lacks any sort of ‘real’ const as provided by C++.
As I was digging into this, I ran across (didn’t save the URL though) a page that appeared to be from one of the language developers that claimed that broad-based read only-ness couldn’t be implemented because other CLR languages wouldn’t have to respect it. This seems to be the same sort of junk argument that both .NET and Java proponents threw at generics before those languages implemented support. Other languages don’t have to respect protected and private tags either (and in C++ any other language can do terrible things through a const &).
The point is to help developers create safe code and allow mutable things to be tagged as immutable in appropriate contexts.
The work around suggested for C# is to implement a full set of parallel interfaces with ‘ReadOnly’ tagged onto the end of their names and all of their methods adjusted to only perform actions that don’t change the object.
To my eyes, this results in cluttered and error prone design. You now have to have IFoo and IFooReadOnly along IBar and IBarReadOnly. The developer must remember that if there’s an IFooReadOnly and they need IBar capabilites they need to select IBarReadOnly when they cast. C++ works hard to provide the ability to tag methods as ‘const safe’ and allow variables and returned references (and pointers) to acquire immutability with const.
I’m going to miss this capability and it seems as if the C# designers are making excuses at this point. They either missed the time for implementing full function read-only (perhaps CIL is missing features that would support this) or they have some religious dislike for supporting it.