Is there a way in C# to use type-matching in a switch statement with the Type variable? I'm writing code that is intended to achieve something similar to this:
public object somefunction(Type targetType)
{
if (targetType == typeof(DateTime))
{
return somevalue;
}
else if (targetType == typeof(TimeSpan))
{
return someothervalue;
}
else
{
return null;
}
}
While not hugely important, my code would be much cleaner if I could write this as:
public object somefunction (Type targetType)
{
switch (targetType)
{
case typeof(DateTime): return somevalue;
case typeof(TimeSpan): return someothervalue;
default: return null;
}
}
However I can't do that because case values must be constants and that rules out using "typeof". Is there a variation on the switch-case statement that does allow you to match Type datatypes?