Since 'At compile time, an element that is typed as dynamic is assumed to support any operation', I would assume that would mean that if I were to use it in a switch statement, the compiler would assume that the dynamic variable would be a supported type for a switch statement.
Contrary to my thinking, the statement
dynamic thing = "thing";
switch (thing) {
case "thing": {
Console.WriteLine("Was a thing.");
Console.ReadKey();
break;
}
default: {
Console.WriteLine("Was not thing.");
Console.ReadKey();
break;
}
}
Gives the compile time error: A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type. So what gives? What's the reason for this limitation?
Because constants used in the case-labels must be compile time constants compatible with the governing type.
You won't be sure about the dynamic variable at the compile time.
How would you know that from which value you will compare in you case-label as dynamic variable can hold any type of value.
Look at this
dynamic thing = "thing";
//and some later time `thing` changed to
thing = 1;
Now think about your case-label (in which type of value you will compare)
Because the case statements must contain only constants, if you cast thing to a string:
dynamic thing = "thing";
switch ((string)thing) {
case "thing": {
Console.WriteLine("Was a thing.");
Console.ReadKey();
break;
}
default: {
Console.WriteLine("Was not thing.");
Console.ReadKey();
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With