'switch on type of generic type parameter

I have some generic method where I want to switch on that type. How do I do that?

This compiles:

void MyMethod<T>()
{
    switch(typeof(T))
    {
        default:
            throw new ArgumentException($"illegal type: {typeof(T).Name}");
    }
}

But this does not:

void MyMethod<T>()
{
    switch(typeof(T))
    {
        case (typeof(string)):
            Debug.WriteLine("compiler error CS0150: A constant value is expected");
            break;
        default:
            throw new ArgumentException($"illegal type: {typeof(T).Name}");
    }
}

I am using C# 10.0.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source