Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Examples of Immutable Types in .Net

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

  • String
  • DateTime

Are there more?

like image 918
Nikhil Agrawal Avatar asked Jul 30 '15 10:07

Nikhil Agrawal


1 Answers

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<T>
  • String
  • The Tuple<…> types introduced with .NET 4 (mentioned in this answer)
  • Uri
  • Version
  • Void

System.Linq.…

  • Lookup<TKey, TElement>
like image 122
8 revs Avatar answered Oct 08 '22 00:10

8 revs