Why does a switch statement on a line fail when a value appears from a ViewBag?

I have the following code on a CSHTML razor page:

@{ var sort = ViewBag.Sort.ToString(); switch (sort) { case "None": Html.Action("SortNone"); break; case "Name": Html.Action("SortName"); break; case "Date": Html.Action("SortDate"); break; } } 

However, this does not work with a compiler error message:

 CS0151: A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type 

But sorting is a line! Rewriting this as a sequence of if / else statements works, but not so elegantly.

+6
source share
1 answer

Try casting, the compiler does not know the return type of ToString (), since it is dynamic.

 var sort = (string)ViewBag.Sort.ToString(); 
+9
source

Source: https://habr.com/ru/post/918420/


All Articles