Switch case in C# - a constant value is expected

johnnie picture johnnie · Sep 29, 2011 · Viewed 158.1k times · Source

My code is as follows:

public static void Output<T>(IEnumerable<T> dataSource) where T : class
{   
    dataSourceName = (typeof(T).Name);
    switch (dataSourceName)
    {
        case (string)typeof(CustomerDetails).Name.ToString(); :
            var t = 123;
            break;
        default:
            Console.WriteLine("Test");
    }
}

But this is not working. The case statement is giving me an error saying that a constant variable is expected. Please help guys thank you!

Answer

deepee1 picture deepee1 · Sep 29, 2011

See C# switch statement limitations - why?

Basically Switches cannot have evaluated statements in the case statement. They must be statically evaluated.