Examples of Immutable Types in .Net

前端 未结 5 1277
执念已碎
执念已碎 2021-02-04 10:22

We know the concept of immutability but need to know few immutable types other than

  • String
  • DateTime

Are there more?

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 11:13

    Some examples from mscorlib:

    • All of the primitive types
    • enums
    • decimal
    • (U)IntPtr
    • DateTime, DateTimeOffset, TimeSpan
    • KeyValuePair<,> - as an opposite, DictionaryEntry is not immutable
    • Tuple<...>
    • (Multicast)Delegate - similarly to strings, always a new instance is returned when it is changed.
    • Guid
    • Version

    Interestingly, string is actually not really immutable; however, we can treat it as a "practically immutable" type, meaning, that the content of a string instance cannot be changed by the public ways (at least, in a safe context). But it has for example a wstrcpy internal method, which is used by the StringBuilder class to manipulate a string instance.

提交回复
热议问题