title: C# returning Dictionary references safely
body: <p>I'm considering three approaches for returning references to internal Dictionary instances (C#) in regards to code safety and impact on the code readability/visually for a project I'm working on.</p>
  
  <p>I've narrowed it down to the following three approaches, but am open to better suggestions. Currently I prefer <strong>#3</strong> as the best balance of safety without extra boiler plate.</p>
  
  <p><strong>1)</strong> Use a second ReadOnlyDictionary instance to wrap internal Dictionary, only ever letting the ReadOnlyDictionary escape the class:</p>
  
  <p><strong>2)</strong> Return the Dictionary instance as an IReadOnlyDictionary, but recasting would allow it to be modified so not as safe as option #1 or #3.</p>
  
  <p><strong>3)</strong> Return Dictionary.ToImmutableDictionary() as a ImmutableDictionary when it escapes the containing class so that the returned object is an immutable view of the inner dictionary, although this will make a new copy for every call incurring a higher cost, that should be fine with small simple dictionaries (which mine are).</p>
  
  <pre><code>    private readonly Dictionary&lt;string, string&gt; innerDictionary = new Dictionary&lt;string, string&gt;();
  
      // Only required for Example #1
      private readonly IReadOnlyDictionary&lt;string, string&gt; readonlyInnerDictionary;
  
      public ExampleClass() {
          // Only required for Example #1
          readonlyInnerDictionary = new ReadOnlyDictionary&lt;string, string&gt;(innerDictionary);
      }   
  
      public IReadOnlyDictionary&lt;string, string&gt; GetExampleOne() {
          // Requires a second dictionary which is more boiler plate but the object being returned is truly readonly
          return readonlyInnerDictionary;     
      }
  
      public IReadOnlyDictionary&lt;string, string&gt; GetExampleTwo() {
          // Requires InnerDictionary be defined as Dictionary (Not IDictionary) but doesn't require the second dictionary be defined
          // which is less boiler plate, but the object returned could be re-cast to it's mutable form meaning it's not truly mutation safe.
          return innerDictionary;
      }
  
      public ImmutableDictionary&lt;string, string&gt; GetExampleThree() {
          // Truly immutable object returned, but a new instance is built for every call; fortunately all of my dictionaries are small (containing at most 9 keys)
          return innerDictionary.ToImmutableDictionary();
      }
  </code></pre>