value of integral type expected switch with dynamic parameter

Belial09 picture Belial09 · Feb 14, 2014 · Viewed 8.2k times · Source

Just out of curiosity.

If I have the following Code

public static string Format(dynamic exception)
{
    switch (exception.GetType().ToString())
    {
        case "test":
            return "Test2";
    }
    return null;
}

i get the error "A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type"

but if i have the following code

public static string Format(dynamic exception)
{
    string test = exception.GetType().ToString();
    switch (test)
    {
        case "test":
            return "Test2";
    }
    return null;
}

everything compiles fine. Whats the Difference if the switch is checking a variable of Type string and ToString()? Or is it because of the Chance to throw an Exception before ToString() is called?

Answer

Jon Senchyna picture Jon Senchyna · Feb 14, 2014

I believe the issue is that your exception variable is a dynamic object. Since it is dynamic, its type is not resolved at compile time, nor are the types of any methods called on it.

As such, the switch statement in the first case has no idea what type the .GetType() method will return, or the .ToString() method. If you want to make it work, you could cast it, like so:

switch (exception.GetType().ToString() as string)

In your second block of code, you are explicitly stating that the result of exception.GetType().ToString() will be a string. In this case, the compiler knows the type of the variable being passed in to the switch statement.

As far as exceptions go: the compiler does not care if your method call could possibly throw an exception. If it does, the exception will bubble up out of the switch statement and be thrown from your method call.

Looking at the content of your Format function, you could achieve the same functionality if you passed in exception as an object. If you're using this function to format Exceptions specifically, you're best off using Exception as the type of your exception parameter.