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 ​

csharp
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()}");
    }
}
csharp
public void Process<T>(T value)
{
    object o = value; // Had to convert to object first
    if (o is int i)
    {
        Console.WriteLine($"Integer: {i * 2}");
    }
    else if (o is string s)
    {
        Console.WriteLine($"String: {s.ToUpper()}");
    }
}

Notes ​

  • 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 ​

Powered by Intracia