✅ Switching on a type object
Is there a way to do a switch on a type object? I've got a function that takes a type and returns an enum value for specific types.
Currently I've had to do it like this:
However, I'd like to be able to make this code more concise.
I could do it with a Dictionary, but if there's a better way of doing this, I'd love to hear it:
5 Replies
You can only use pattern matching in a switch statement, if you have an object, not the type object itself. So you have to rely on a dictionary, or maybe even switch on the name of the type.
Okay - thanks - that's good to know
I'm happy with the dictionary approach. I made the actual dictionary a private static readonly field, so it isn't re-generating each time
I think there is some syntax like
but it's not really better than if/else 😄
in fact i'm pretty sure it's a lot worse
the compiler can optimize
if (typeof(T) == typeof(int)) ...
Thanks - I think I'll stick with the ifs then