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
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: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: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:
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.