Switch case and generics checking

Another way to do switch on generic is:

switch (typeof(T))
{
    case Type intType when intType == typeof(int):
        ...
    case Type decimalType when decimalType == typeof(decimal):
        ...
    default:
        ...
}

Note that when as a case guard in switch expressions was introduced in C# 7.0/Visual Studio 2017.


In modern C#:

public static string FormatWithCommaSeperator<T>(T value) where T : struct
{
    switch (value)
    {
        case int i:
            return $"integer {i}";
        case double d:
            return $"double {d}";
    }
}

You can use the TypeCode enum for switch:

switch (Type.GetTypeCode(typeof(T)))
{
    case TypeCode.Int32:
       ...
       break;
    case TypeCode.Decimal:
       ...
       break;
}

Since C# 7.0 you can use pattern matching:

switch (obj)
{
    case int i:
       ...
       break;
    case decimal d:
       ...
       break;
    case UserDefinedType u:
       ...
       break;
}

Beginning with C# 8.0 you can use switch expressions:

string result = obj switch {
    int i => $"Integer {i}",
    decimal d => $"Decimal {d}",
    UserDefinedType u => "User defined {u}",
    _ => "unexpected type"
};

Tags:

C#

Generics