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.
I have the following foreach loops in my view:
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) {
...
}
Model.CustomObjectList1 through Model.CustomObjectList6 are all defined as List<CustomObject>
, as I have to place these custom objects into different buckets and iterate through each to display on the view.
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 outside the loops at the end of the page:
<input type="hidden" id="otherObjectId" name="otherObjectId" value="@Model.OtherObject.ID" />
After making that change and trying to test my change, I now get a NullReferenceException error after iterating through Model.CustomObjectList6.
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.
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.
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.
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)...
for(int x=0; x<10; x++) {
CustomObject rt = Model.CustomObjectList6[x];
...
}
...I still get the NullReferenceExceptionError and the debugger highlights x<10
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<10, and then throws the error.