C# immutable int

前端 未结 3 501
野性不改
野性不改 2021-02-05 12:38

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\         


        
相关标签:
3条回答
  • 2021-02-05 12:47

    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.

    0 讨论(0)
  • 2021-02-05 13:02

    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.

    0 讨论(0)
  • 2021-02-05 13:04

    Although this may sound obvious I'll add a couple of lines that helped me to understand in case someone has the same confusion.

    There are various kinds of mutability but generally when people say "immutable" they mean that class has members that cannot be changed.

    String is probably storing characters in an array, which is not accessible and cannot be changed via methods, that's why string is immutable. Operation + on strings always returns a new string.

    int is probably storing it's value in member "Value" which anyway is inaccessible, and that's why cannot be changed. All operations on int return new int, and this value is copied to variable, because it's a value type.

    0 讨论(0)
提交回复
热议问题