Weird switch behavior in .NET 4

Posted by RaYell on Stack Overflow See other posts from Stack Overflow or by RaYell
Published on 2010-06-02T12:54:44Z Indexed on 2010/06/02 13:03 UTC
Read the original article Hit count: 396

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about .net-4.0