Use variable outside switch statement + asp.net mvc

In my Index Action in my Controller I have this:

public ActionResult Index(string sortOrder)
{
    var model;
    ViewBag.CitySortParm = String.IsNullOrEmpty(sortOrder) ? "City_desc" : "";
    switch (sortOrder)
    {
        case "City_desc":
            model = this.UnitOfWork.AddressRepository.Get().OrderBy(a => a.City);
            break;
    }
    return View(model);
}

This doesn't work, I always get the error: Implicitly-typed local variables must be initialized

Why doesn't this work and how can I fix this?

Jon Skeet
people
quotationmark

Why doesn't this work

Two reasons:

  • You're trying to use var without specifying an initial value. You can't do that - the compiler can't infer the type.
  • You're trying to read from the model variable when it may not be initialized - if sortOrder isn't City_desc what would you expect to be returned? And what would that type be?

and how can I fix this?

That depends on what you want to happen if sortOrder isn't City_desc. Work out what value you'd want to return, and make sure it's returned.

Basically, you can't read from a local variable until it's definitely assigned - in other words, until the compiler can prove (by the rules of C#) that by the time you get there, it will have been assigned a value.

In terms of the implicit typing - are you always going to use the same type for your view? If so, just explicitly declare the type of model, as well as fixing the definite assignment part. If not, I'd consider returning within the switch/case statement - I don't think your model local variable is actually helping you much.

people

See more on this question at Stackoverflow