skip to Main Content

Assume the following code:

public async Task<IActionResult> Weather(string cityName)
{
    if (cityName == null)
    {
        return View(await _weatherService.GetWeather(cityName));
    }
    return RedirectToAction("Weather");
}

I would like to restructure the code to make use of a switch statement evaluating the expression await _weatherService.GetWeather(cityName) and then referencing it in the cases without having to assign it. Is this possible in any way or can’t the evaluated expression, here being an object, not be referenced in any way without assigning it first?

What I could do (making conditionals from the object rather than the string value being given:

WeatherConvertedObject w = await _weatherService.GetWeather(cityName);
switch (w)
{
    case null: return RedirectToAction("Weather");
    case not null: return View(await _weatherService.GetWeather(cityName));
}

What I want to do (somehow if it is possible?):

switch (await _weatherService.GetWeather(cityName))
{
    case null: return RedirectToAction("Weather");
    case not null: return View(this);
        //this illustration simply a reference to the evaluated object - this won't compile
}

2

Answers


  1. Whether or not your code flow is correct, there are many ways of writing what you want, though switch isn’t it. One way to do it would be something like this:

    if(await _weatherService.GetWeather(cityName) is { } weather)  // implied not null
        return View(weather);
    return RedirectToAction("Weather");
    

    You also have the ternary operator to write it as an expression, also based on pattern matching like above.

    Edit: well, you can also write it with a switch statement (or expression) if you really want to:

    switch (await _weatherService.GetWeather(cityName))
    {
        case null: return RedirectToAction("Weather");
        case { } weather: return View(weather);
    }
    
    Login or Signup to reply.
  2. I think you confused a lot of people by including a (probably incorrect) conditional on the cityName variable, and then proceeding to ignore that conditional when you described the behavior you’re looking for in your switch statement.

    You could rewrite your method like this:

    public async Task<IActionResult> Weather(string cityName)
    {
        return cityName switch
        {
            not null when await _weatherService.GetWeather(cityName) is {} w => View(w),
            _ => RedirectToAction("Weather")
        };
    }
    

    Note that this fixes what I believe was an error in your original code by using the cityName when it is not null. I’m also using switch expressions rather than switch statements.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search