title: Dictionary.Count performance
body: <p><strong>This question seems to be nonsense. The behaviour cannot be reproduced reliably.</strong></p>
  
  <p>Comparing the following test programs, I observed a <em>huge</em> performance difference between the first and the second of the following examples (the first example is by factor ten slower than the second):</p>
  
  <p>First example (slow):</p>
  
  <pre><code>interface IWrappedDict {
      int Number { get; }
      void AddSomething (string k, string v);
  }
  
  class WrappedDict : IWrappedDict {
      private Dictionary&lt;string, string&gt; dict = new Dictionary&lt;string,string&gt; ();
  
  
      public void AddSomething (string k, string v) {
          dict.Add (k, v);
      }
  
      public int Number { get { return dict.Count; } }
  }
  
  class TestClass {
      private IWrappedDict wrappedDict;
  
      public TestClass (IWrappedDict theWrappedDict) {
          wrappedDict = theWrappedDict;
      }
  
      public void DoSomething () {
          // this function does the performance test
          for (int i = 0; i &lt; 1000000; ++i) {
              var c = wrappedDict.Number; wrappedDict.AddSomething (...);
          }
      }
  }
  </code></pre>
  
  <p>Second example (fast):</p>
  
  <pre><code>// IWrappedDict as above
  class WrappedDict : IWrappedDict {
      private Dictionary&lt;string, string&gt; dict = new Dictionary&lt;string,string&gt; ();
      private int c = 0;
  
      public void AddSomething (string k, string v) {
          dict.Add (k, v); ++ c;
      }
  
      public int Number { get { return c; } }
  }
  // rest as above
  </code></pre>
  
  <p>Funnily, the difference vanishes (the first example gets fast as well) if I change the type of the member variable <code>TestClass.wrappedDict</code> from <code>IWrappedDict</code> to <code>WrappedDict</code>. My interpretation of this is that <code>Dictionary.Count</code> re-counts the elements every time it is accessed and that potential caching of the number of elements is done by compiler optimization only.</p>
  
  <p>Can anybody confirm this? Is there any way to get the number of elements in a <code>Dictionary</code> in a performant way?</p>