I have some C# code in my ASP.NET MVC3 project that’s throwing an exception claiming:
Cannot perform runtime binding on a null reference
The line of code throwing the exception is:
ViewBag.Foo[i].Name = allSpark[i].Users.Name;
This is the code block:
ViewBag.Foo = new myAllSparkModelType[allSpark.Length];
for (int i = 0; i < allSpark.Length; i++)
{
ViewBag.Foo[i].Name = allSpark[i].Users.Name;
...
}
When I set a breakpoint and inspect allSpark[i].Users.Name, it definitely has a value (e.g. “Fred”).
If I comment out this line of code, the next line (which is similar code) then throws the same exception.
So the problem is either that allSpark[i].Users.Name is a null reference (Which I’ve confirmed isn’t) or I can’t just use the ViewBag like I am. If it’s the latter, I’m confused as I thought that the ViewBag could be used this way.
Look at this code:
ViewBag.Foois initialized, but each element ofViewBag.Foowill benull, assumingmyDataModelTypeis a class. When you create an array, each element is initialized to the default value of the element type – and for reference types, that default value is null.You need to create a new object for each element: