Recently, I read a lot of literature on Types of values โโand types of links and their differences. This question surrounds the topic of variability and immutability of value types.
Based on what I read, it seems that value types in .NET should be written in such a way that they are immutable; that is, after they are assigned a value, the value of this type in memory never changes. Only subsequent copies of the type can create new instances in memory with new values โโbased on the original. It would seem that volatility in .NET is evil.
To clarify the understanding of immutability (for my own sanity and for others), I have demonstrated this below:
DateTime and TimeSpan are examples of immutable structures, because once a value has been assigned to an instance, the value of this instance cannot be changed, this is evident thanks to readonly properties:
DateTime dt = new DateTime(); DateTime newdt = dt.AddDays(2); // Okay, new value stored in newdt newdt.Year = 1945; // Error, cannot write to readonly property
However, immutability can be confusing when looking for primitive types such as
Int32 ,
Double or
Char , because the types seem mutable, but my gut feeling is that immutability is actually handled transparently through the CLR; take, for example, the following operations (I commented on some very simple x86 equivalents to understand how immutability is handled in terms of a primitive type)
int x = 0; // xor eax, eax; 'clear register to 0 // push eax; 'push eax (0) onto the stack x = 5; // pop eax; 'pop stack (0) into eax // mov eax, 5; 'eax = 5 // push eax; 'push eax (5) onto the stack x++; // pop eax; 'pop stack (5) into eax // add eax, 1; 'eax = 5 + 1 // push eax; 'push eax (6) onto the stack
Everything is good and good so far; Microsoft seems to be doing a good job of introducing immutability into its value types; but then we start finding bad apples, and the subelements that make volatility look good, and lul developers look in the false sense of security!
I am talking about Point , Size , Rectangle (and several others) in System.Drawing .
Suddenly we are given the opportunity to change the type of value according to its properties, and I have a theory why this is possible; take for example the following code
Point p = new Point(); pX = 100; pY = 200;
However, as said, I had a theory as to why these structures are mutable:
- Microsoft just wanted to simplify working with these structures.
- They are compatible with their own GDI / GDI + calls, so their behavior was developed around their own C / C ++ counterparts.
So finally my questions are:
- I fully embraced and understood the immutability and variability?
- Should developers strive to create immutable structures, as a rule?
- When is it acceptable to create mutable structures?