I thought I understood what Immutable meant, however I don\'t understand why the following compiles and works:
DateTime dt = DateTime.Now;
Console.WriteLine
If an instance of a non-trivial structure type is stored in a writable storage location (non-readonly
field, local variable, array slot, etc.), all of its fields will be mutable. If an instance is stored in a non-writable storage location (a readonly
field, a compiler-generated temporary value, etc.), then none of its fields will be mutable. The concept of an "immutable structure type" is a misnomer, since the statement:
myStruct1 = myStruct2; // Assume variables are of the same structure type
will, if myStruct1
is writable, replace all public and private fields of myStruct1
with the corresponding fields of myStruct2
; if myStruct1
isn't writable, the statement will generate a compile-time error. The code for the structure gets no say in the matter, and won't even be notified that the assignment as taken place.
Although DateTime
provides no means by which an existing DateTime
instance can be modified except by whole-structure assignment, it can do nothing to prevent code from overwriting the fields of one instance with the contents of another, as happens with dateTimeVariable = DateTime.Now;
.