Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# immutable int

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?

like image 261
Georgii Oleinikov Avatar asked Dec 23 '12 06:12

Georgii Oleinikov


2 Answers

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.

like image 84
Eric Lippert Avatar answered Oct 05 '22 05:10

Eric Lippert


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.

like image 28
Marc Gravell Avatar answered Oct 05 '22 04:10

Marc Gravell