J
Jon Skeet [C# MVP]
Lucian Wischik said:My original observation was that, yes, there is language support to
demonstrate that a function returns you an "immutable" thing, in the
sense that the function will no longer alter it -- make it return a
struct! So that counts (as per thread title) of an instance "when why
and where" a struct should be used. It's for when your design calls
for something immutable by the sender, and you want it robustly
compiler-supportedly immutable against the possibility of later
programmer mistakes. (and sometimes just when the weight of putting
every single field into the constructor is too much...)
Except that if your struct contains a mutable reference type variable,
the data within that could change. It won't refer to a different
object, but the data within the object could change.
Note that using structs doesn't help when you want to return more than
one value - such as a collection. If you return an array of value
types, for instance, the array could still change contents behind the
scenes.
I think it's interesting that, if a function returns IEnumerable<T>,
then it gives a compiler-supported guarantee that the *recipient* will
not subsequently alter the list. But it's impossible for any choice of
interface to make similar guarantees about the *sender*.
True. Documentation is key here, IMO.
I agree it's an issue - but it's one which hasn't proved to be too
worrying in real life, IMO. It's like the type-safety given by generic
collections - it's more useful from a confidence, automatic
documentation and value type efficiency standpoint than to actually get
rid of bugs, because in my experience there aren't many times when you
*actually* try to use something in (say) an ArrayList and choose the
wrong type.