title: Why would typeof(Foo) ever return null?
body: <p>Occasionally, I see that <code>typeof(Foo)</code> returns null.  Why would this happen?</p>
  
  <p>This is in C#, .NET 3.5.</p>
  
  <p>I thought it might have something to do with the assembly containing the type not yet being loaded, but a test app shows that the assembly is loaded at the start of the method where <code>typeof</code> is used.  </p>
  
  <p>Any ideas?</p>
  
  <hr>
  
  <p><strong>Update 1</strong></p>
  
  <ul>
  <li>I can't provide a reproducible sample as this happens on a huge application</li>
  <li>When I say 'occasionally' I mean in the same method in my application but during various instances.  Also, when it fails once when running, it'll fail every time for that instance of the application.</li>
  </ul>
  
  <hr>
  
  <p><strong>Update 2</strong></p>
  
  <p>The application in question uses a huuuuuge amount of memory and runs on 32bit XP.  I'm thinking maybe it's a TypeLoadException or OutOfMemoryException that's somehow being swallowed (but I can't see how, as I've tried this with first-chance exceptions turned on in the debugger).</p>
  
  <hr>
  
  <p><strong>Update 3</strong></p>
  
  <p>Ran into the same issue just now.  Here's the stack trace:
  <img src="https://i.stack.imgur.com/yY4qz.png" alt="enter image description here">
  The code up to this point is literally just:</p>
  
  <pre><code>Type tradeType = typeof(MyTradeType)
  TradeFactory.CreateTrade(tradeType)
  </code></pre>
  
  <p><em>(before, it was <code>..CreateTrade(typeof(MyTradeType))</code> so <strong>I couldn't actually tell if the <code>typeof</code> returned null</strong>)</em></p>
  
  <p>So, it looks like <strong><code>typeof()</code> isn't returning null</strong> but it's <strong>getting set to null by the time it ends up in the <code>CreateTrade</code> method</strong>.</p>
  
  <p>The exception (<code>NullReferenceException</code>) has a <code>HResult</code> property of <code>0x80004003</code> (<code>Invalid pointer</code>).  A call to <code>System.Runtime.InteropServices.Marshal.GetLastWin32Error( )</code> (in the Immediate Window) returns <code>127 (The specified procedure could not be found)</code>.
  I've looked in the Modules window and the module that contains this type and method has been loaded and there doesn't look to be any loader errors.</p>
  
  <hr>