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.

 1public class Program
 2{
 3    public static async Task Main()
 4    {
 5        Console.WriteLine(WithAnIfElse<string>("abc"));
 6        Console.WriteLine(WithAnIfElse<int>(123));
 7
 8        Console.WriteLine(WithASwitchAndReturn<string>("abc"));
 9        Console.WriteLine(WithASwitchAndReturn<int>(123));
10
11        Console.WriteLine(WithASwitchAndExpressionBody<string>("abc"));
12        Console.WriteLine(WithASwitchAndExpressionBody<int>(123));
13
14    }
15    public static string WithAnIfElse<T>(T item)
16    {
17        if (item is int intValue)
18        {
19            return $"It's a number: {intValue}";
20        }
21        else if (item is string stringValue)
22        {
23            return $"It's a string: {stringValue}";
24        }
25        return "";
26    }
27
28    public static string WithASwitchAndReturn<T>(T item)
29    {
30        string value = item switch
31        {
32            int => $"It's a number: {item.ToString()}",
33            string => $"It's a string: {item as string}",
34            _ => ""
35        };
36        return value;
37    }
38
39    public static string WithASwitchAndExpressionBody<T>(T item) =>
40        item switch
41        {
42            int => $"It's a number: {item.ToString()}",
43            string => $"It's a string: {item as string}",
44        };
45}
comments powered by Disqus

Related