Reputation: 9196
I have the following code in 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 is failing 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 sort is a string! Rewriting this as a series of if/else statements works, but is not as elegant.
Upvotes: 7
Views: 5022
Reputation: 9298
Try casting, the compiler doesn't know the return type of ToString() because it is dynamic.
var sort = (string)ViewBag.Sort.ToString();
Upvotes: 11