C# immutable int

前端 未结 3 502
野性不改
野性不改 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.

提交回复
热议问题