String immutability in C#

前端 未结 6 1803
暖寄归人
暖寄归人 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 19:54

    Can i create a completely immutable type?

    Yes. Have a constructor to set private fields, get only properties and no methods.

    Is there any reason to use such code apart from performance concerns?

    One example: such types don't require locks to be safely used from multiple concurrent threads, this makes correct code easier to write (no locks to get wrong).

    Additional: it is always possible for sufficiently privileged code to bypass .NET protections: either reflection to read and write to private fields, or unsafe code to directly manipulate an object's memory.

    This is true outside of .NET, a privileged process (i.e. with a process or thread token with one of the "God" privileges, e.g. Take Ownership enabled) can break into any other process load dlls, inject threads running arbitrary code, read or write memory (including overriding execute prevention etc.). The integrity of the system is only as strong as the cooperation of the owner of the system.

提交回复
热议问题