Wesley Wigham
Wesley Wigham

Reputation: 261

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?

Upvotes: 4

Views: 3335

Answers (5)

Martijn
Martijn

Reputation: 1719

Since C# 8 you can use pattern matching switch expressions for this:

dynamic thing;

thing switch
{
    int intThing => $"it's an int, incremented: {intThing + 1}",
    string stringThing => $"it's a string, uppercase: {stringThing.ToUpper()}",
    _ => "I have no idea what this is"
};

Upvotes: 0

Ashish Kumar
Ashish Kumar

Reputation: 1

Upgrade your VS, In VS 2017 switch statement has accepted the dynamic type.

Happy coding :)

Upvotes: -2

T McKeown
T McKeown

Reputation: 12847

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;
        }
    }

Upvotes: 2

Sachin
Sachin

Reputation: 40970

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)

Upvotes: 3

dburner
dburner

Reputation: 1007

Because the case statements must contain only constants. Thus limiting the switch only to "native" data (int, double, float, etc.) and strings. Dynamic may hold all kinds of data including reference types.

Upvotes: 0

Related Questions