title: How to handle possibility of null variables in Razor code?
body: <p>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.</p>
  
  <p>Here's a simple example of what's happening:</p>
  
  <pre><code>@{
      if (ViewBag.Foo != null)
      {
          double[] bar = new double[ViewBag.Foo.Length];
      }
  }
  </code></pre>
  
  <p>Later on in the code, I'll have something like this:</p>
  
  <pre><code>@if (ViewBag.Foo != null)
  {
      ...some code that uses `bar` goes here ...
  }
  </code></pre>
  
  <p>With that code, I get errors when <code>ViewBag.Foo</code> actually is null. I get an exception thrown complaining about the second section of code that uses <code>bar</code> and it not being in scope . However, in the execution, that second section will always be skipped.</p>
  
  <p>After messing with it for awhile, I just did this instead:</p>
  
  <pre><code>double[] bar;
  @{
      if (ViewBag.Foo != null)
      {
          bar = new double[ViewBag.Foo.Length];
      }
  }
  else
  {
      bar = new double[1];
  }
  </code></pre>
  
  <p>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?</p>