String immutability in C#

前端 未结 6 1790
暖寄归人
暖寄归人 2020-12-13 19:31

I was curious how the StringBuilder class is implemented internally, so I decided to check out Mono\'s source code and compare it with Reflector\'s disassembled code of the

6条回答
  •  不思量自难忘°
    2020-12-13 20:06

    There is no completely immutable type, a class that is immutable is that because it doesn't allow any outside code to alter it. Using reflection or unsafe code you can still change it's values.

    You can use the readonly keyword to create an immutable variable, but that works only for value types. If you use it on a reference type, it's only the reference that is protected, not the object that it points to.

    There are several reasons for immutable types, like performance and robustness.

    The fact that strings are known to be immutable (outside the StringBuilder) means that the compiler can make optimisations based on that. The compiler never has to produce code to copy a string to protect it from being changed when it's passed as a parameter.

    Objects created from immutable types can also be safely passed between threads. As they can't be changed, there is no risk for different threads changing them at the same time, so there is no need to synchonise access to them.

    Immutable types can be used to avoid coding errors. If you know that a value should not be changed, it's generally a good idea to make sure that it can't be changed by mistake.

提交回复
热议问题