title: NullReferenceException while objects involved are valid
body: <p><code>NullReferenceException</code> is being thrown on a line on which all involved objects are valid. <code>StackTrace</code> shows the line # is 432.</p>
  
  <p>The code is </p>
  
  <p><img src="https://i.stack.imgur.com/uegpp.png" alt="enter image description here"></p>
  
  <p>Here, <code>Flags</code> and <code>tempFlags</code> both are datatables. Data types of columns of both datatables are primitive (decimal, datetime, short). The application is a multithreaded application and the code snippet belongs to the thread function. <code>Flags</code> is decalred at instance level i.e. shared to all threads while <code>tempFlags</code> is declared inside the thread function.</p>
  
  <p>Here at this particular instance of time the <code>Flags</code> contains 1946 records and <code>tempFlags</code> contains 1. So, why is this NullReferenceException ??</p>
  
  <p><strong>Edit # 1</strong></p>
  
  <pre><code>ex.InnerException
  null
  ex.StackTrace
  at System.Data.DataTable.RecordStateChanged(Int32 record1, DataViewRowState oldState1, DataViewRowState newState1, Int32 record2, DataViewRowState oldState2, DataViewRowState newState2)
  at System.Data.DataTable.InsertRow(DataRow row, Int64 proposedID)
  at System.Data.DataTable.MergeRow(DataRow row, DataRow targetRow, Boolean preserveChanges, Index idxSearch)
  at System.Data.Merger.MergeTable(DataTable src, DataTable dst)
  at System.Data.Merger.MergeTableData(DataTable src)
  at System.Data.Merger.MergeTable(DataTable src)
  at System.Data.DataTable.Merge(DataTable table, Boolean preserveChanges, MissingSchemaAction missingSchemaAction)
  at System.Data.DataTable.Merge(DataTable table)
  at [...].cs:line 432"
  ex.Data
      {System.Collections.ListDictionaryInternal}
          [System.Collections.ListDictionaryInternal]: {System.Collections.ListDictionaryInternal}
          IsFixedSize: false
          IsReadOnly: false
          Keys: {System.Collections.ListDictionaryInternal.NodeKeyValueCollection}
          Values: {System.Collections.ListDictionaryInternal.NodeKeyValueCollection}
  ex.Message
  "Object reference not set to an instance of an object."
  ex.Source
  "System.Data"
  </code></pre>
  
  <p><strong>Edit # 2</strong></p>
  
  <p>It looks the Merge statement is not thread safe as after putting line 432 inside a lock, the exception is gone, SO FAR.</p>