NullReferenceException on foreach loop when list is populated (not null) : <p>I was going to write up a question on this very peculiar issue I was having, but while writing the question found my own answer.  So I figured I would go ahead and post this for the benefit of others and give my answer below.</p>

<p>I have the following foreach loops in my view:</p>

<pre><code>foreach(CustomObject rt in Model.CustomObjectList1) {
   ...
}
foreach(CustomObject rt in Model.CustomObjectList2) {
   ...
}
foreach(CustomObject rt in Model.CustomObjectList3) {
   ...
}
foreach(CustomObject rt in Model.CustomObjectList4) {
   ...
}
foreach(CustomObject rt in Model.CustomObjectList5) {
   ...
}
foreach(CustomObject rt in Model.CustomObjectList6) {
   ...
}
</code></pre>

<p>Model.CustomObjectList1 through Model.CustomObjectList6 are all defined as <code>List&lt;CustomObject&gt;</code>, as I have to place these custom objects into different buckets and iterate through each to display on the view.</p>

<p>Before today, this code has worked fine for a long time.  Today, I made an edit to the view to add the following hidden input field <strong>outside</strong> the loops at the end of the page:  </p>

<p><code>&lt;input type="hidden" id="otherObjectId" name="otherObjectId" value="@Model.OtherObject.ID" /&gt;</code></p>

<p>After making that change and trying to test my change, I now get a NullReferenceException error after iterating through Model.CustomObjectList6.</p>

<p>Debugging, I can see it looping through all the objects that populate Model.CustomObjectList6, and then after reaching the end of what should be the final iteration the code execution goes back to the top of the foreach loop and throws the NullReferenceException, with the debugger highlighting the "in" in the loop declaration.</p>

<p>I only get this problem on Model.CustomObjectList6.  List 1-5 iterate just fine with no errors.  I've also tried loading different datasets into this view as different users get different results by design, and the issue persists.</p>

<p>For example, if there are 10 objects in the list, I step through the code for each of the 10 objects and then get the error as if it is trying to execute an 11th iteration that doesn't exist.</p>

<p>To top it off, even if I change the iteration to a standard loop like this (since I know Model.CustomObjectList6 contains exactly 10, non-null items)...</p>

<pre><code>for(int x=0; x&lt;10; x++) {
   CustomObject rt = Model.CustomObjectList6[x];
   ...
}
</code></pre>

<p>...I still get the NullReferenceExceptionError and the debugger highlights <code>x&lt;10</code> as the point of the NullReferenceException error.  I can watch it loop through the 10 proper iterations, go back to the top (where it highlights x++), next step it tries to evaluate x&lt;10, and then throws the error.</p>
