This question already has an answer here:
- Immutable collections? 10 answers
It seems to me there is an extreme lack of safe, immutable collection types for .NET, in particular BCL but I've not seen much work done outside either. Do anyone have any pointers to a (preferably) production quality, fast, immutable collections library for .NET. A fast list type is essential. I'm not yet prepared to switch to F#.
*Edit: Note to searchers, this is being rolled into the BCL soon: .NET immutable collections
I wrote an
ImmutableList<T>
class some time ago :All methods that modify the collection return a modified copy. In order to fulfill with the
IList<T>
interface contract, the standard Add/Remove/Delete/Clear methods are implemented explicitly, but they throw anInvalidOperationException
.This class uses a few non-standard extension methods, here they are :
And here's a helper class to create instances of
ImmutableList<T>
:Here's a usage example :
I can't say it's production quality, as I haven't tested it thoroughly, but so far it seems to work just fine...
You might want to take a look at the
Microsoft.FSharp.Collections
namespace in theFSharp.Core
assembly. You do not have to program in F# to make use of these types.Keep in mind that the names will be different when used from outside F#. For example, the
Map
in F# is known asFSharpMap
from C#.You may look at Extras or System.collections.concurrent tutorial
C5 springs to mind, but I'm not sure how fast it is. It has been around for years, and is very stable.
Additionally,
List<T>.AsReadOnly()
does the job rather well IMO, but unfortunately there is no equivalent for dictionaries or arbitraryICollection<T>
's.The .NET BCL team has released a Immutable Collections preview for .NET 4.5