Skip to content

Commit abb1ad7

Browse files
authored
Merge pull request #12 from devlights/csharp7-new-feature-pattern-variable-switch-statement
Add C# 7.0 Pattern variable with switch-statement example
2 parents 4cb197e + c6287f9 commit abb1ad7

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
using TryCSharp.Common;
2+
3+
namespace TryCSharp.Samples.CSharp7
4+
{
5+
[Sample]
6+
public class PatternVariableWithSwitchStatement : IExecutable
7+
{
8+
public void Execute()
9+
{
10+
// C# 7.0 から Pattern Variables の概念が導入された
11+
// switch 文でもパターンが利用できるようになった
12+
this.SwitchWithPattern(100);
13+
this.SwitchWithPattern("hello");
14+
this.SwitchWithPattern(true);
15+
this.SwitchWithPattern(null);
16+
}
17+
18+
private void SwitchWithPattern(object x)
19+
{
20+
// 型で振り分け
21+
switch (x)
22+
{
23+
case int i:
24+
Output.WriteLine($"x is int: {i}");
25+
break;
26+
case string s:
27+
Output.WriteLine($"x is string: {s}");
28+
break;
29+
case bool b:
30+
Output.WriteLine($"x is bool: {b}");
31+
break;
32+
case null:
33+
Output.WriteLine($"x is null");
34+
break;
35+
}
36+
37+
// case に when で条件を付けることが可能
38+
switch (x)
39+
{
40+
case int i when i == 10:
41+
Output.WriteLine($"x is int, value is 10");
42+
break;
43+
case int i when i == 100:
44+
Output.WriteLine($"x is int, value is 100");
45+
break;
46+
case string s when s == "hello":
47+
Output.WriteLine($"x is string, value is hello");
48+
break;
49+
case string s when s == "world":
50+
Output.WriteLine($"x is string, value is world");
51+
break;
52+
case bool b when b == true:
53+
Output.WriteLine($"x is bool, value is true");
54+
break;
55+
case bool b when b == false:
56+
Output.WriteLine($"x is bool, value is false");
57+
break;
58+
}
59+
}
60+
}
61+
}

0 commit comments

Comments
 (0)