Examples of Immutable Types in .Net

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

    I am not sure if you're looking for publicly immutable types in .NET or types totally immutable at all. Furthermore you want to take care of only the public types in .NET? The deeper problem is defining what forms immutability. Does a class that only has

    public readonly int[] Numbers;
    

    makes it immutable? The Numbers itself can't be changed but its contents can be. You get the idea.

    Anyway you could inspect yourself programmatically. For deeper nested checks you will need recursion (which I wont do here)

    Load all assemblies you wanna check, and do something like (not tested)

    var immutables = AppDomain.CurrentDomain
                    .GetAssemblies()
                    .SelectMany(t => t.GetTypes())
                    .Where(t => t
                               .GetProperties(your binding flags depending on your definition)
                               .All(p => !p.CanWrite) 
                             && t
                               .GetFields(your binding flags depending on your definition)
                               .All(f => f.IsInitOnly)
                    .ToList();
    

    Even this wont be enough for finding immutability of collection types. Some of the immutable collection types (though not a part of default .NET core) can be found here: Immutable Collections


    Some notable immutables:

    • some class types like String, Tuple, anonymous types
    • most structs (notable exceptions include most enumerators)
    • enums
    • delegates
    • immutable collection types like

      ImmutableArray (prerelease version)

      ImmutableDictionary

      ImmutableSortedDictionary

      ImmutableHashSet

      ImmutableList

      ImmutableQueue

      ImmutableSortedSet

      ImmutableStack

提交回复
热议问题