- A
ReadOnlyDictionary
can be initialized once via constructor, then you can’t add or remove items from it (they throwNotSupportedException
s). It’s useful if you want to ensure that it won’t be modified while it’s sent across multiple layers of your application. - An
ImmutableDictionary
has methods to modify it likeAdd
orRemove
, but they will create a new dictionary and return that, the original one remains unchanged and the copy of the new immutable dictionary is returned.
Note that:
- You initialize the
ReadOnlyDictionary
by passing another dictionary instance to the constructor. That explains why aReadOnlyDictionary
is mutable (if the underlying dictionary is modified). It’s just a wrapper that is protected from direct changes. - You can’t use a constructor for
ImmutableDictionary
: How can I create a new instance of ImmutableDictionary?
That also explains why the ReadOnlyDictionary
is not thread-safe (better: it’s as thread-safe as the underlying dictionary). The ImmutableDictionary
is thread-safe because you can’t modify the original instance (neither directly nor indirectly). All methods that “modify” it actually return a new instance.
But if you need a thread-safe dictionary and it’s not necessary that it’s immutable, use a ConcurrentDictionary
instead.