title: C#: Why do I get an OutOfMemoryException on a NullReferenceException?
body: <p>I got an <strong><code>OutOfMemoryException</code></strong> earlier and couldn't figure out what it was for. It made no sense at all. Dug around in my code, and suddenly remembered that somewhere had forgotten to check for null, and in this particular case it was (and should be) exactly that. That shouldn't cause an <code>OutOfMemoryException</code> in my opinion, but I fixed it anywas of course. And when I did, the exception didn't appear anymore!</p>
  
  <p>So I removed the check again and studied the exception I got some more. And turns out it had an <strong>InnerException of type <code>NullReferenceException</code></strong> and a stack trace which of course made <em>a lot</em> more sense. </p>
  
  <p>But why did I get an <code>OutOfMemoryException</code>? This has never happend to me before... makes no sense to me...</p>
  
  <hr>
  
  <p>Would love to give some more context, but can't really say much without having to upload the whole project, which I can't (And which you wouldn't want to read through anyways :p). But the specific place it happend looks like this:</p>
  
  <pre><code>            {
                  foreach (var exportParameter in exportParameters)
                  {
                      // Copy to local
                      var ep = exportParameter;
  
                      // Load stored values from db
                      ...
                  }
  
                  int i = 1;
                  exportParameters
                      .OrderBy(ø =&gt; ø.Sequence)
                      .ForEach(ø =&gt; { if (!ø.Locked) ø.Sequence = i++; });
              }
  </code></pre>
  
  <p>The fix was to put an <code>if(exportParameters != null)</code> before the code block. <code>exportParameters</code> is a <code>List&lt;ExportParameter&gt;</code>, except in the failing case in which it was <code>null</code>.</p>