Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can a C# switch statement not accept the 'dynamic' type?

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?

like image 697
Wesley Wigham Avatar asked Oct 24 '25 22:10

Wesley Wigham


2 Answers

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)

like image 116
Sachin Avatar answered Oct 27 '25 12:10

Sachin


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;
        }
    }
like image 40
T McKeown Avatar answered Oct 27 '25 13:10

T McKeown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!