In Java strings are immutable. If we have a string and make changes to it, we get new string referenced by the same variable:
String str = "abc";
str += "def"; // now str refers to another piece in the heap containing "abcdef"
// while "abc" is still somewhere in the heap until taken by GC
It's been said that int and double are immutable in C#. Does it mean that when we have int and later change it, we would get new int "pointed" by the same variable? Same thing but with stack.
int i = 1;
i += 1; // same thing: in the stack there is value 2 to which variable
// i is attached, and somewhere in the stack there is value 1
Is that correct? If not, in what way is int immutable?
To follow up on Marc's (perfectly acceptable) answer: Integer values are immutable but integer variables may vary. That's why they're called "variables".
Integer values are immutable: if you have the value that is the number 12, there's no way to make it odd, no way to paint it blue, and so on. If you try to make it odd by, say, adding one, then you end up with a different value, 13. Maybe you store that value in the variable that used to contain 12, but that doesn't change any property of 12. 12 stays exactly the same as it was before.
You haven't changed (and cannot change) something about the int; you have assigned a new int value (and discarded the old value). Thus it is immutable.
Consider a more complex struct:
var x = new FooStruct(123);
x.Value = 456; // mutate
x.SomeMethodThatChangedInternalState(); // mutate
x = new FooStruct(456); // **not** a mutate; this is a *reassignment*
However, there is no "pointing" here. The struct is directly on the stack (in this case): no references involved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With