/
PatternMatchingCSharp8.cs
51 lines (47 loc) · 1.78 KB
/
PatternMatchingCSharp8.cs
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
46
47
48
49
50
51
using CheatSheet.Extra;
namespace CheatSheet.CSharp8
{
/// <summary>
/// A more flexible way to handle alternative flows of execution, this way of coding partially resembles functional programming.
/// For more detail: https://docs.microsoft.com/en-us/archive/msdn-magazine/2019/may/csharp-8-0-pattern-matching-in-csharp-8-0
/// </summary>
public static class PatternMatchingCSharp8
{
public static void Run()
{
var person = new Person
{
Name = "Mark"
};
// Old way.
string oldConsoleValue;
switch (person.Name)
{
case "Mark":
oldConsoleValue = "Hi I'm Mark";
break;
case null:
throw new ArgumentNullException();
default:
throw new InvalidOperationException();
}
Console.WriteLine(oldConsoleValue);
// New way.
var newConsoleValue = person.Name switch
{
"Mark" => "Hi! I'm Mark",
null => throw new ArgumentNullException(),
_ => throw new NotImplementedException()
};
Console.WriteLine(newConsoleValue);
var extendedNewConsoleValue = person switch
{
Person nullPerson when nullPerson?.Name == null => throw new ArgumentNullException(),
Person { Name: "Mark" } => "Hi! I'm Mark",
Person personWithNameStartedInM when personWithNameStartedInM.Name.StartsWith('M') => "Hi! My name starts with an M",
_ => throw new InvalidOperationException()
};
Console.WriteLine(extendedNewConsoleValue);
}
}
}