I have some Razor code that has conditional logic based on whether a certain array variable is set. I'm having a heck of a time figuring out the best way to handle when it's null and I'm not happy with my kludgy solution.
Here's a simple example of what's happening:
@{
if (ViewBag.Foo != null)
{
double[] bar = new double[ViewBag.Foo.Length];
}
}
Later on in the code, I'll have something like this:
@if (ViewBag.Foo != null)
{
...some code that uses `bar` goes here ...
}
With that code, I get errors when ViewBag.Foo
actually is null. I get an exception thrown complaining about the second section of code that uses bar
and it not being in scope . However, in the execution, that second section will always be skipped.
After messing with it for awhile, I just did this instead:
double[] bar;
@{
if (ViewBag.Foo != null)
{
bar = new double[ViewBag.Foo.Length];
}
}
else
{
bar = new double[1];
}
With this change, the code works when ViewBag.Foo is null and non-null. There's gotta be a better way to handle this... anyone?