Hyun-jik Bae <im***********@paran.comwrote:
Is there any way to prohibit writing values to an object A retrieved from
another object B if B gives A for read only purpose?
Unfortunately not. (I disagree with Nick on this front - I think there
are plenty of times when it would be useful to return something in a
read-only way.)
C++ has the idea of "const-correctness" and it's been put forward many
times both for .NET and Java. The main difficulties as I understand
them are:
1) Making the syntax simple but expressive. For instance, if I return
an array of Foo, you might want to declare that the receiver can't
change the contents of the array, or can't change the Foo instances
referred to by the array, or both. We've seen how generics can make for
some pretty long type declarations - const correctness would do the
same kind of thing.
2) Unless it's supported by the standard libraries, it's not nearly as
much use - and making the standard libraries const-correct in
retrospect would quite possibly break a lot of things.
Now admittedly, your example code isn't ideal: B.xx would usually be
exposed as a property instead of a public field, and the property could
be read-only, but I assume in real life other uses of B would need it
to be writable.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog:
http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too