title: Impossible NullReferenceException?
body: <p>I'm investigating an exception that a colleague just got while running an application through Visual Studio 2010:</p>
  
  <pre class="lang-none prettyprint-override"><code>System.NullReferenceException was unhandled by user code
    Message=Object reference not set to an instance of an object.
    Source=mscorlib
    StackTrace:
         at System.Collections.Generic.GenericEqualityComparer`1.Equals(T x, T y)
         at System.Collections.Concurrent.ConcurrentDictionary`2.TryGetValue(TKey key, TValue&amp; value)
         at xxxxxxx.xxxxxxx.xxxxxxx.RepositoryBase`2.GetFromCache(TIdentity id) 
  </code></pre>
  
  <p>Using <a href="http://en.wikipedia.org/wiki/.NET_Reflector" rel="nofollow">.NET Reflector</a>, I have looked at the code for <br><code>GenericEqualityComparer&lt;T&gt;.Equals(T x, T y)</code>, and I can't see any possible cause for a <code>NullReferenceException</code>.</p>
  
  <pre><code>//GenericEqualityComparer&lt;T&gt;.Equals(T x, T y) from mscorlib 4.0.30319.269
  public override bool Equals(T x, T y)
  {
      if (x != null)
      {
          return ((y != null) &amp;&amp; x.Equals(y));
      }
      if (y != null)
      {
          return false;
      }
      return true;
  }
  </code></pre>
  
  <p>The type of <code>T,</code> <code>TKey</code> and <code>TIdentity</code> are all the same type in this <a href="http://en.wikipedia.org/wiki/Stack_trace" rel="nofollow">stack trace</a>.</p>
  
  <p>The type is a custom type called <code>Identity</code> that implements <code>IEquatable&lt;Identity&gt;</code>. It is immutable and cannot be constructed with null values for the fields that it uses in its implementation of <code>Equals(Identity other)</code>. It also overrides <code>Equals(object obj)</code> like this:</p>
  
  <pre><code>public override bool Equals(object obj)
  {
      if ((object)this == obj)
      {
          return true;
      }
      return Equals(obj as Identity);
  }
  
  public bool Equals(Identity other)
  {
      if ((object)this == (object)other)
      {
          return true;
      }
      if ((object)other == null)
      {
          return false;
      }
      if (!FieldA.Equals(other.FieldA))
      {
          return false;
      }
      return FieldB.Equals(other.FieldB);
  }
  </code></pre>
  
  <p>I have a fairly exhaustive set of unit tests around the <code>Equals</code> implementations. So, it will happily accept a value of null for other/obj and return false as expected.</p>
  
  <p>The type does not either override the <code>==</code> operators nor <code>!=</code> operators.</p>
  
  <p>Even so, I would expect to see my class on top of the stack trace if the exception was being thrown from the implementation of <code>Equals(Identity other)</code> in my <code>Identity</code> class, but it says the <code>NullReferenceException</code> is coming from <code>mscorlib</code>.</p>
  
  <p>I'm running on .NET Framework version 4.0.30319.269.</p>
  
  <p>I don't have a memory dump, and I have not seen this before and have not reproduced it since. Still, I'm obliged to investigate and to be absolutely certain that it is not being caused by our code and that it won't happen in production.</p>
  
  <p>So, the real question is: What caused this exception?</p>
  
  <ul>
  <li>Bug in mscorlib (seems highly unlikely)</li>
  <li>Transient memory corruption on the machine (possible, hard to back up with evidence)</li>
  <li>Other?</li>
  </ul>
  
  <p><strong>* Updates in response to Jordão *</strong></p>
  
  <blockquote>
    <p>Is it possible to call the method with an object that is not an Identity?</p>
  </blockquote>
  
  <p>The <code>ConcurrentDictionary&lt;TKey, TValue&gt;</code> is typed such that <code>TKey</code> = <code>Identity</code> and nothing subclasses <code>Identity</code>. So, I can't see how it could be possible.</p>
  
  <blockquote>
    <p>Is it possible to call the method with null?</p>
  </blockquote>
  
  <p>Unit tests cover the scenario of calling all of the <code>Equals</code> implementations with null.</p>
  
  <blockquote>
    <p>What version of the code is the stack trace from? Maybe some older version susceptible to the exception?</p>
  </blockquote>
  
  <p>I'm analyzing the same code that generated the exception. I have checked that the version of the .NET Framework running on my colleagues computer is also 4.0.30319.269.</p>
  
  <blockquote>
    <p>Any multithreaded scenario could cause the exception? These are usually hard to reproduce, but might be worth investigating.</p>
  </blockquote>
  
  <p>Yes, the code is multi-threaded and intended to be. So, that is why I'm using a <code>ConcurrentDictionary</code>.</p>
  
  <p><strong>* Followup related to response from Jalal Aldeen Saa'd *</strong></p>
  
  <p>I would have thought that a race condition where some other thread sets <code>x</code> to <code>null</code> could only be the cause if the parameter <code>x</code> was passed by reference using the 'ref' keyword. I set out to validate that theory with the following code:</p>
  
  <pre><code>ManualResetEvent TestForNull = new ManualResetEvent(false);
  ManualResetEvent SetToNull = new ManualResetEvent(false);
  
  [TestMethod]
  public void Test()
  {
      var x = new object();
      var y = new object();
  
      var t = Task.Factory.StartNew(() =&gt;
      {
          return Equals(x, y);
      });
      TestForNull.WaitOne(); //wait until x has been tested for null value
      x = null;
      SetToNull.Set(); //signal that x has now been set to null
      var result = t.Result;
      Assert.IsFalse(result);
  }
  
  public bool Equals&lt;T&gt;(T x, T y)
  {
      if (x != null)
      {
          TestForNull.Set(); //signal that we have determined that x was not null
          SetToNull.WaitOne(); //wait for original x value to be set to null
          //would fail here if setting the outer scope x to null affected
          //the value of x in this scope
          return ((y != null) &amp;&amp; x.Equals(y)); 
      }
      if (y != null)
      {
          return false;
      }
      return true;
  }
  </code></pre>
  
  <p>and the test completes without errors.</p>
  
  <p>I can force that behavior if I change the signature to pass <code>x</code> and <code>y</code> by reference (that is, <code>public bool Equals&lt;T&gt;(ref T x, ref T y) then the test fails with a</code>NullReferenceException<code>, but this does not match the method signature of</code>GenericEqualityComparer.Equals(T x, T y)`.</p>