The other day I was testing MVC some code, and after my form submission my application kept on coming back with an exception:

Cannot perform runtime binding on a null reference

Ok cool, I thought – I hadn’t set a variable properly.  Confusion reigned when I stepped through the code, just before the model was returned to the view and found, lo and behold – the variable in error is NOT null and was very much a valid data item.

What?  Why would the compiler tell me that my variable (using the Html.Hidden MVC Helper method) was empty when it clearly wasn’t.

So then I commented out the code, only for it to happen on the next line.

What?

After a few minutes of asking my PC “What?” and “why?”, I realised that the debugger was telling me lies, and that there was an issue with a null reference – just not in that point.

Turns out I’d added a ViewBag data item in the GET method, but in the POST method I hadn’t re-populated it.  This was an IEnumerable which was the basis of a list, hence the reason why it was needed when the view was returned to the model.

Once that was rectified, all was right in the world.  Phew.

Moral of the story – Don’t believe everything you read, not even .NET debugger notices!