Skip to content

Generic type pattern matching C# 7.1code reduction

Use pattern matching with generic type constraints.

C# 7.0 introduced pattern matching with the is operator, allowing you to test and extract values in a single expression. However, it didn't work with generic type parameters, forcing developers to use workarounds or explicit casts.

C# 7.1 removes this limitation by allowing pattern matching to work with generic type parameters, making generic methods more concise and readable.

Code

C#
public void Process<T>(T value)
{
    if (value is int i)
    {
        Console.WriteLine($"Integer: {i * 2}");
    }
    else if (value is string s)
    {
        Console.WriteLine($"String: {s.ToUpper()}");
    }
}
C#
public void Process<T>(T value)
{
    if (typeof(T) == typeof(int))
    {
        int i = (int)(object)value;
        Console.WriteLine($"Integer: {i * 2}");
    }
    else if (typeof(T) == typeof(string))
    {
        string s = (string)(object)value;
        Console.WriteLine($"String: {s.ToUpper()}");
    }
}

Notes

  • Pattern matching with generic type parameters requires boxing for value types
  • You can use any pattern matching syntax including type patterns, constant patterns, and var patterns
  • This works with both the is operator and switch statements

More information