0

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?

  • https://stackoverflow.com/questions/708911/using-case-switch-and-gettype-to-determine-the-object – Chetan Jul 28 '21 at 02:10
  • https://stackoverflow.com/questions/298976/is-there-a-better-alternative-than-this-to-switch-on-type – Chetan Jul 28 '21 at 02:10
  • Does this answer your question? [c# 7.0: switch on System.Type](https://stackoverflow.com/questions/43080505/c-sharp-7-0-switch-on-system-type) and [How to use switch-case on a Type?](https://stackoverflow.com/questions/7542793/how-to-use-switch-case-on-a-type) –  Jul 28 '21 at 02:41

0 Answers0