C# immutable int

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

提交回复
热议问题