I have a problem understanding what's causes the compilation error in the code below:
static class Program
{
static void Main()
{
dynamic x = "";
var test = foo(x);
if (test == "test")
{
Console.WriteLine(test);
}
switch (test)
{
case "test":
Console.WriteLine(test);
break;
}
}
private static string foo(object item)
{
return "bar";
}
}
The error I get is in switch (test)
line:
A switch expression or case label must be a bool, char, string, integral,
enum, or corresponding nullable type.
Intellisence shows me that foo operation will be resolved on runtime, which is fine because I'm using a dynamic type as a param. However I don't understand how if
condition compiles fine when switch doesn't.
Code above is just simplified version of what I have in my application (VSTO) which appeared after migrating the app from VSTO3 to VSTO4 when one method in VSTO was changed to return dynamic
type values instead of object
.
Can anyone give me an explanation what's the problem. I know how to resolve it but I'd like to understand what's happening.