A Few Ways of Pattern Matching with C#

This is mostly a post for future me for when I forget how I used pattern matching.

In a previous post, I used pattern matching with a WhenAny of different types of task, so I started playing around more with pattern matching and found at least three ways to use them for my scenario - in an if/else, a switch with a return, and a switch in an expression body.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class Program
{
    public static async Task Main()
    {
        Console.WriteLine(WithAnIfElse<string>("abc"));
        Console.WriteLine(WithAnIfElse<int>(123));

        Console.WriteLine(WithASwitchAndReturn<string>("abc"));
        Console.WriteLine(WithASwitchAndReturn<int>(123));

        Console.WriteLine(WithASwitchAndExpressionBody<string>("abc"));
        Console.WriteLine(WithASwitchAndExpressionBody<int>(123));

    }
    public static string WithAnIfElse<T>(T item)
    {
        if (item is int intValue)
        {
            return $"It's a number: {intValue}";
        }
        else if (item is string stringValue)
        {
            return $"It's a string: {stringValue}";
        }
        return "";
    }

    public static string WithASwitchAndReturn<T>(T item)
    {
        string value = item switch
        {
            int => $"It's a number: {item.ToString()}",
            string => $"It's a string: {item as string}",
            _ => ""
        };
        return value;
    }

    public static string WithASwitchAndExpressionBody<T>(T item) =>
        item switch
        {
            int => $"It's a number: {item.ToString()}",
            string => $"It's a string: {item as string}",
        };
}
comments powered by Disqus

Related