Switch case and generics checking

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"
};

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)