C
C#2y ago
Hugh

✅ 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:
private static MyValueType GetValueTypeFromType(Type value)
{
if(value == typeof(string))
{
return MyValueType.String;
}

if(value == typeof(bool))
{
return MyValueType.Bool;
}

if(value == typeof(int))
{
return MyValueType.Int;
}

return MyValueType.Invalid;
}
private static MyValueType GetValueTypeFromType(Type value)
{
if(value == typeof(string))
{
return MyValueType.String;
}

if(value == typeof(bool))
{
return MyValueType.Bool;
}

if(value == typeof(int))
{
return MyValueType.Int;
}

return MyValueType.Invalid;
}
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:
Dictionary<Type, MyValueType> valueTypes = new()
{
[typeof(string)] = MyValueType.String,
[typeof(bool)] = MyValueType.Bool,
[typeof(int)] = MyValueType.Int,
};
Dictionary<Type, MyValueType> valueTypes = new()
{
[typeof(string)] = MyValueType.String,
[typeof(bool)] = MyValueType.Bool,
[typeof(int)] = MyValueType.Int,
};
5 Replies
HimmDawg
HimmDawg2y ago
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.
Hugh
HughOP2y ago
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
HimmDawg
HimmDawg2y ago
I think there is some syntax like
switch (type)
{
case Type t1 when t1 == typeof(int): ...
}
switch (type)
{
case Type t1 when t1 == typeof(int): ...
}
but it's not really better than if/else 😄
ero
ero2y ago
in fact i'm pretty sure it's a lot worse the compiler can optimize if (typeof(T) == typeof(int)) ...
Hugh
HughOP2y ago
Thanks - I think I'll stick with the ifs then
Want results from more Discord servers?
Add your server