<p><strong>Is there anything built into the core C# libraries that can give me an immutable Dictionary?</strong>  </p>

<p>Something along the lines of <em>Java's</em>:</p>

<pre><code>Collections.unmodifiableMap(myMap);
</code></pre>

<p>And just to clarify, I am not looking to stop the keys / values themselves from being changed, just the structure of the Dictionary.  I want something that fails fast and loud if any of IDictionary's mutator methods are called (<code>Add, Remove, Clear</code>).</p>

[{'answer_id': 35045, 'author': 'Kevin Dente', 'author_id': 9, 'author_profile': 'https://Stackoverflow.com/users/9', 'pm_score': 2, 'selected': False, 'text': "<p>I don't think so. There is a way to create a read-only List and read only Collection, but I don't think there's a built in read only Dictionary. System.ServiceModel has a ReadOnlyDictinoary implementation, but its internal. Probably wouldn't be too hard to copy it though, using Reflector, or to simply create your own from scratch. It basically wraps an Dictionary and throws when a mutator is called.</p>\n"}, {'answer_id': 35059, 'author': 'Serhat Ozgel', 'author_id': 31505, 'author_profile': 'https://Stackoverflow.com/users/31505', 'pm_score': 5, 'selected': False, 'text': '<p>As far as I know, there is not. But maybe you can copy some code (and learn a lot) from these articles:</p>\n\n<ul>\n<li><a href="https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-one-kinds-of-immutability" rel="nofollow noreferrer">Immutability in C# Part One: Kinds of Immutability</a></li>\n<li><a href="https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-two-a-simple-immutable-stack" rel="nofollow noreferrer">Immutability in C# Part Two: A Simple Immutable Stack</a></li>\n<li><a href="https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-three-a-covariant-immutable-stack" rel="nofollow noreferrer">Immutability in C# Part Three: A Covariant Immutable Stack</a></li>\n<li><a href="https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-four-an-immutable-queue" rel="nofollow noreferrer">Immutability in C# Part Four: An Immutable Queue</a></li>\n<li><a href="https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-five-lolz" rel="nofollow noreferrer">Immutability in C# Part Five: LOLZ</a></li>\n<li><a href="https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-six-a-simple-binary-tree" rel="nofollow noreferrer">Immutability in C# Part Six: A Simple Binary Tree</a></li>\n<li><a href="https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-seven-more-on-binary-trees" rel="nofollow noreferrer">Immutability in C# Part Seven: More on Binary Trees</a></li>\n<li><a href="https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-eight-even-more-on-binary-trees" rel="nofollow noreferrer">Immutability in C# Part Eight: Even More On Binary Trees</a></li>\n<li><a href="https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-nine-academic-plus-my-avl-tree-implementation" rel="nofollow noreferrer">Immutability in C# Part Nine: Academic? Plus my AVL tree implementation</a></li>\n<li><a href="https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-10-a-double-ended-queue" rel="nofollow noreferrer">Immutability in C# Part 10: A double-ended queue</a></li>\n<li><a href="https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-eleven-a-working-double-ended-queue" rel="nofollow noreferrer">Immutability in C# Part Eleven: A working double-ended queue</a></li>\n</ul>\n'}, {'answer_id': 35099, 'author': 'Scott Dorman', 'author_id': 1559, 'author_profile': 'https://Stackoverflow.com/users/1559', 'pm_score': 1, 'selected': False, 'text': '<p>"Out of the box" there is not a way to do this. You can create one by deriving your own Dictionary class and implementing the restrictions you need.</p>\n'}, {'answer_id': 35144, 'author': 'chakrit', 'author_id': 3055, 'author_profile': 'https://Stackoverflow.com/users/3055', 'pm_score': 2, 'selected': False, 'text': '<p>One workaround might be, throw a new list of KeyValuePair from the Dictionary to keep the original unmodified.</p>\n\n<pre><code>var dict = new Dictionary&lt;string, string&gt;();\n\ndict.Add("Hello", "World");\ndict.Add("The", "Quick");\ndict.Add("Brown", "Fox");\n\nvar dictCopy = dict.Select(\n    item =&gt; new KeyValuePair&lt;string, string&gt;(item.Key, item.Value));\n\n// returns dictCopy;\n</code></pre>\n\n<p>This way the original dictionary won\'t get modified.</p>\n'}, {'answer_id': 35666, 'author': 'dbkk', 'author_id': 838, 'author_profile': 'https://Stackoverflow.com/users/838', 'pm_score': 7, 'selected': True, 'text': '<p>No, but a wrapper is rather trivial:</p>\n\n<pre><code>public class ReadOnlyDictionary&lt;TKey, TValue&gt; : IDictionary&lt;TKey, TValue&gt;\n{\n    IDictionary&lt;TKey, TValue&gt; _dict;\n\n    public ReadOnlyDictionary(IDictionary&lt;TKey, TValue&gt; backingDict)\n    {\n        _dict = backingDict;\n    }\n\n    public void Add(TKey key, TValue value)\n    {\n        throw new InvalidOperationException();\n    }\n\n    public bool ContainsKey(TKey key)\n    {\n        return _dict.ContainsKey(key);\n    }\n\n    public ICollection&lt;TKey&gt; Keys\n    {\n        get { return _dict.Keys; }\n    }\n\n    public bool Remove(TKey key)\n    {\n        throw new InvalidOperationException();\n    }\n\n    public bool TryGetValue(TKey key, out TValue value)\n    {\n        return _dict.TryGetValue(key, out value);\n    }\n\n    public ICollection&lt;TValue&gt; Values\n    {\n        get { return _dict.Values; }\n    }\n\n    public TValue this[TKey key]\n    {\n        get { return _dict[key]; }\n        set { throw new InvalidOperationException(); }\n    }\n\n    public void Add(KeyValuePair&lt;TKey, TValue&gt; item)\n    {\n        throw new InvalidOperationException();\n    }\n\n    public void Clear()\n    {\n        throw new InvalidOperationException();\n    }\n\n    public bool Contains(KeyValuePair&lt;TKey, TValue&gt; item)\n    {\n        return _dict.Contains(item);\n    }\n\n    public void CopyTo(KeyValuePair&lt;TKey, TValue&gt;[] array, int arrayIndex)\n    {\n        _dict.CopyTo(array, arrayIndex);\n    }\n\n    public int Count\n    {\n        get { return _dict.Count; }\n    }\n\n    public bool IsReadOnly\n    {\n        get { return true; }\n    }\n\n    public bool Remove(KeyValuePair&lt;TKey, TValue&gt; item)\n    {\n        throw new InvalidOperationException();\n    }\n\n    public IEnumerator&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; GetEnumerator()\n    {\n        return _dict.GetEnumerator();\n    }\n\n    System.Collections.IEnumerator \n           System.Collections.IEnumerable.GetEnumerator()\n    {\n        return ((System.Collections.IEnumerable)_dict).GetEnumerator();\n    }\n}\n</code></pre>\n\n<p>Obviously, you can change the this[] setter above if you want to allow modifying values. </p>\n'}, {'answer_id': 503344, 'author': 'Olmo', 'author_id': 38670, 'author_profile': 'https://Stackoverflow.com/users/38670', 'pm_score': 1, 'selected': False, 'text': '<p>I\'ve found an implementation of an Inmutable (not READONLY) implementation of a AVLTree for C# here. </p>\n\n<p>An AVL tree has logarithmic (not constant) cost on each operation, but stills fast.</p>\n\n<p><a href="http://csharpfeeds.com/post/7512/Immutability_in_Csharp_Part_Nine_Academic_Plus_my_AVL_tree_implementation.aspx" rel="nofollow noreferrer">http://csharpfeeds.com/post/7512/Immutability_in_Csharp_Part_Nine_Academic_Plus_my_AVL_tree_implementation.aspx</a></p>\n'}, {'answer_id': 1104668, 'author': 'Sarah Vessels', 'author_id': 38743, 'author_profile': 'https://Stackoverflow.com/users/38743', 'pm_score': 2, 'selected': False, 'text': '<p>Adding onto <a href="https://stackoverflow.com/questions/35002/does-c-have-a-way-of-giving-me-an-immutable-dictionary/35666#35666">dbkk\'s answer</a>, I wanted to be able to use an object initializer when first creating my ReadOnlyDictionary.  I made the following modifications:</p>\n\n<pre><code>private readonly int _finalCount;\n\n/// &lt;summary&gt;\n/// Takes a count of how many key-value pairs should be allowed.\n/// Dictionary can be modified to add up to that many pairs, but no\n/// pair can be modified or removed after it is added.  Intended to be\n/// used with an object initializer.\n/// &lt;/summary&gt;\n/// &lt;param name="count"&gt;&lt;/param&gt;\npublic ReadOnlyDictionary(int count)\n{\n    _dict = new SortedDictionary&lt;TKey, TValue&gt;();\n    _finalCount = count;\n}\n\n/// &lt;summary&gt;\n/// To allow object initializers, this will allow the dictionary to be\n/// added onto up to a certain number, specifically the count set in\n/// one of the constructors.\n/// &lt;/summary&gt;\n/// &lt;param name="key"&gt;&lt;/param&gt;\n/// &lt;param name="value"&gt;&lt;/param&gt;\npublic void Add(TKey key, TValue value)\n{\n    if (_dict.Keys.Count &lt; _finalCount)\n    {\n        _dict.Add(key, value);\n    }\n    else\n    {\n        throw new InvalidOperationException(\n            "Cannot add pair &lt;" + key + ", " + value + "&gt; because " +\n            "maximum final count " + _finalCount + " has been reached"\n        );\n    }\n}\n</code></pre>\n\n<p>Now I can use the class like so:</p>\n\n<pre><code>ReadOnlyDictionary&lt;string, string&gt; Fields =\n    new ReadOnlyDictionary&lt;string, string&gt;(2)\n        {\n            {"hey", "now"},\n            {"you", "there"}\n        };\n</code></pre>\n'}, {'answer_id': 1428665, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Since Linq, there is a generic interface <strong>ILookup</strong>. \nRead more in <a href="http://msdn.microsoft.com/en-us/library/bb534291.aspx" rel="nofollow noreferrer">MSDN</a>.</p>\n\n<p>Therefore, To simply get immutable dictionary you may call:</p>\n\n<pre><code>using System.Linq;\n// (...)\nvar dictionary = new Dictionary&lt;string, object&gt;();\n// (...)\nvar read_only = dictionary.ToLookup(kv =&gt; kv.Key, kv =&gt; kv.Value);\n</code></pre>\n'}, {'answer_id': 4057390, 'author': 'SoftwareRockstar', 'author_id': 491973, 'author_profile': 'https://Stackoverflow.com/users/491973', 'pm_score': -1, 'selected': False, 'text': '<p>There\'s also another alternative as I have described at:</p>\n\n<p><a href="http://www.softwarerockstar.com/2010/10/readonlydictionary-tkey-tvalue/" rel="nofollow">http://www.softwarerockstar.com/2010/10/readonlydictionary-tkey-tvalue/</a></p>\n\n<p>Essentially it\'s a subclass of ReadOnlyCollection>, which gets the work done in a more elegant manner.  Elegant in the sense that it has compile-time support for making the Dictionary read-only rather than throwing exceptions from methods that modify the items within it.</p>\n'}, {'answer_id': 6471072, 'author': 'David Moles', 'author_id': 27358, 'author_profile': 'https://Stackoverflow.com/users/27358', 'pm_score': 2, 'selected': False, 'text': '<p>The open-source <a href="http://powercollections.codeplex.com/" rel="nofollow">PowerCollections</a> library includes a read-only dictionary wrapper (as well as read-only wrappers for pretty much everything else), accessible via a static <code>ReadOnly()</code> method on the <code>Algorithms</code> class. </p>\n'}, {'answer_id': 8585197, 'author': 'uglybugger', 'author_id': 94697, 'author_profile': 'https://Stackoverflow.com/users/94697', 'pm_score': 1, 'selected': False, 'text': '<p>You could try something like this:</p>\n\n<pre><code>private readonly Dictionary&lt;string, string&gt; _someDictionary;\n\npublic IEnumerable&lt;KeyValuePair&lt;string, string&gt;&gt; SomeDictionary\n{\n    get { return _someDictionary; }\n}\n</code></pre>\n\n<p>This would remove the mutability problem in favour of having your caller have to either convert it to their own dictionary:</p>\n\n<pre><code>foo.SomeDictionary.ToDictionary(kvp =&gt; kvp.Key);\n</code></pre>\n\n<p>... or use a comparison operation on the key rather than an index lookup, e.g.:</p>\n\n<pre><code>foo.SomeDictionary.First(kvp =&gt; kvp.Key == "SomeKey");\n</code></pre>\n'}, {'answer_id': 12463109, 'author': 'Dylan Meador', 'author_id': 684831, 'author_profile': 'https://Stackoverflow.com/users/684831', 'pm_score': 4, 'selected': False, 'text': '<p>With the release of .NET 4.5, there is a new <a href="http://msdn.microsoft.com/en-us/library/gg712875.aspx" rel="nofollow noreferrer">ReadOnlyDictionary</a> class. You simply pass an <code>IDictionary</code> to the constructor to create the immutable dictionary.</p>\n\n<p><a href="https://stackoverflow.com/a/678404/684831">Here</a> is a helpful extension method which can be used to simplify creating the readonly dictionary.</p>\n'}, {'answer_id': 19387663, 'author': 'Fredrik Solhaug', 'author_id': 2883636, 'author_profile': 'https://Stackoverflow.com/users/2883636', 'pm_score': 1, 'selected': False, 'text': "<p>In general it is a much better idea to not pass around any dictionaries in the first place (if you don't HAVE to).</p>\n\n<p>Instead - create a domain-object with an interface that doesn't offer any methods <em>modifying</em> the dictionary (that it wraps). Instead offering required LookUp-method that retrieves element from the dictionary by key (bonus is it makes it easier to use than a dictionary as well).</p>\n\n<pre><code>public interface IMyDomainObjectDictionary \n{\n    IMyDomainObject GetMyDomainObject(string key);\n}\n\ninternal class MyDomainObjectDictionary : IMyDomainObjectDictionary \n{\n    public IDictionary&lt;string, IMyDomainObject&gt; _myDictionary { get; set; }\n    public IMyDomainObject GetMyDomainObject(string key)         {.._myDictionary .TryGetValue..etc...};\n}\n</code></pre>\n"}, {'answer_id': 61090094, 'author': 'Andrej Lucansky', 'author_id': 1503963, 'author_profile': 'https://Stackoverflow.com/users/1503963', 'pm_score': 2, 'selected': False, 'text': '<p>I know this is a very old question, but I somehow found it in 2020 so I suppose it may be worth noting that there is a way to create immutable dictionary now:</p>\n\n<p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.immutable.immutabledictionary.toimmutabledictionary?view=netcore-3.1" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/api/system.collections.immutable.immutabledictionary.toimmutabledictionary?view=netcore-3.1</a></p>\n\n<p>Usage:</p>\n\n<pre><code>using System.Collections.Immutable;\n\npublic MyClass {\n    private Dictionary&lt;KeyType, ValueType&gt; myDictionary;\n\n    public ImmutableDictionary&lt;KeyType, ValueType&gt; GetImmutable()\n    {\n        return myDictionary.ToImmutableDictionary();\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/35002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1853/']