One of the main problems with fields in the public readonly class in .net is that, from the point of view of external code, the only thing the readonly declaration does is to mark the field with the readonly attribute (I forgot the spelling and casing), although some languages โโwill abide by such attributes in the external code, the language can ignore such attributes, if it chooses so. If an object with public readonly fields is exposed to code written in a language that ignores the readonly attribute, this code can write to such fields as easily as if the attribute did not exist.
Structures are another matter. If the structure stored in the foo field has a boz proper name boz , then code that can write to foo can be written to foo.boz , and code that cannot write to foo cannot be written to foo.boz >, regardless whether boz public or private or is supposed to be modified or unchanged. This is because if foo1 is a structure of the same type, the operator foo = foo1 does not make foo reference to the same instance as foo1 , but works by changing all public and private fields in foo to match the values โโof the corresponding fields in foo1 .
Boxed types are even worse; if there is an Object that contains an instance with a short instance of any type of value, this value can be replaced with another type of this type. Even presumably immutable types, such as Int32 , when inserted, behave like mutable reference types.
Therefore, when using structure types, it is necessary to ensure immutability, while maintaining structures in private fields of the exact type of structure. An attempt to make immutable structure fields can cause types with a lot of trouble to work, but will not have a real impact on the variability or immutability of instances of the structure.
source share