Examples of Immutable Types in .Net

前端 未结 5 1280
执念已碎
执念已碎 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:16

    A list of immutable types in the framework class library follows below. (Feel free to expand it!)

    System.…

    • All primitive value types: (Note: not all value types are immutable!)
      • Byte and SByte
      • Int16 and UInt16
      • Int32 and UInt32
      • Int64 and UInt64
      • IntPtr
      • Single
      • Double
    • Decimal
    • All anonymous types created by the compiler (new { ... } in C#, New With { ... } in VB.NET) (Wrong for two reasons: These types are not in the FCL, and apparently VB.NET types are mutable.)
    • All enumeration types (enum, Enum)
    • All delegate types. (see this answer. While it might seem that delegates are mutable (since you can do things like obj.PropertyChanged += callback, it's actually the obj.PropertyChanged reference that is mutated to point to a newly constructed delegate instance; the original delegate instance stays unchanged.)
    • DateTime, TimeSpan (mentioned in this answer) and DateTimeOffset
    • DBNull
    • Guid
    • Nullable
    • String
    • The Tuple<…> types introduced with .NET 4 (mentioned in this answer)
    • Uri
    • Version
    • Void

    System.Linq.…

    • Lookup

提交回复
热议问题