What is the point of this C# Dictionary<,> optimization?
<p>I'm using C# 4.0. "Optimize code" in Visual Studio is turned on.</p>

<p>Consider the following code, in a class:</p>

<pre><code>Dictionary&lt;int, int&gt; dictionary = new Dictionary&lt;int, int&gt;();

public void IncrementDictionary(int key) {
    if (!dictionary.ContainsKey(key)) {
        dictionary[key] = 1;
    } else {
        dictionary[key]++;
    }
}
</code></pre>

<p>Here, a call to <code>IncrementDictionary</code> does one of two things:</p>

<ul>
<li>If no value exists for <code>key</code>, then a value is created and initialized to 1.</li>
<li>If a value exists, the value is incremented by 1.</li>
</ul>

<p>Now watch what happens when I use ILSpy to decompile the result:</p>

<pre><code>Dictionary&lt;int, int&gt; dictionary = new Dictionary&lt;int, int&gt;();

public void IncrementDictionary(int key) {
    if (!dictionary.ContainsKey(key)) {
        dictionary[key] = 1;
        return;
    }
    Dictionary&lt;int, int&gt; dictionary2;
    (dictionary2 = dictionary)[key] = dictionary2[key] + 1;
}
</code></pre>

<p><strong>Note:</strong> In the actual production code using this, the optimizer/compiler also creates: <code>int key2 = key;</code> and uses <code>key2</code> in the final line.</p>

<p>Ok, <code>var</code> has been replaced by <code>Dictionary&lt;int, int&gt;</code>, which is expected. And the <code>if</code> statement was simplified to add a <code>return</code> instead of using an <code>else</code>.</p>

<p><strong>But why the heck was a new reference to the original dictionary created?</strong></p>
