1

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.

Kjara
  • 2,504
  • 15
  • 42
  • 3
    `case Type stringType when stringType == typeof(string):` – Ralf Apr 06 '22 at 12:56
  • 5
    If you need to check the type of a generic method that almost always means you should rethink your design. Maybe instead of generics you should instead have overloads for the various specific types. – juharr Apr 06 '22 at 13:00
  • 2
    my bad, then how about [this answer](https://stackoverflow.com/a/61746384/5174469) ? I still think that it sounds like an X/Y problem and I agree with juharr – Mong Zhu Apr 06 '22 at 13:04
  • @juharr The real generic method goes like this: `static T To(this MyType input)`. It is an extension method that should convert `MyType` to `T`, where I have a range of possible types that can be `T`. Since the types that `T` can represent are pure data types, I do not want to pollute them with conversion methods. That's why I'm doing it as an extension method, and that's why I cannot be really generic but must use a `switch`. – Kjara Apr 06 '22 at 13:05
  • 1
    @MongZhu The object is `input`, which is always of type `MyType`. But I need to switch on `T`, of which I do not have an object. – Kjara Apr 06 '22 at 13:07
  • Personally that sounds like you need methods like `static This ToThis(this MyType input)` and `static That ToThat(this MyType input)`. – juharr Apr 06 '22 at 13:16
  • @Kjara you're right, sorry for the confusion – Mong Zhu Apr 06 '22 at 13:20

0 Answers0