Skip to content

Commit db8e616

Browse files
authored
add generic pattern match sample (#803)
* add generic pattern match sample Supports dotnet/docs#10334 * add last output line.
1 parent 6f797d6 commit db8e616

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// <Snippet1>
2+
using System;
3+
using System.Collections;
4+
using System.Collections.Generic;
5+
using System.Linq;
6+
7+
class Example
8+
{
9+
static void Main(string[] args)
10+
{
11+
int[] values = { 2, 4, 6, 8, 10 };
12+
ShowCollectionInformation(values);
13+
14+
var names = new List<string>();
15+
names.AddRange( new string[] { "Adam", "Abigail", "Bertrand", "Bridgette" } );
16+
ShowCollectionInformation(names);
17+
18+
List<int> numbers = null;
19+
ShowCollectionInformation(numbers);
20+
}
21+
22+
private static void ShowCollectionInformation<T>(T coll)
23+
{
24+
switch (coll)
25+
{
26+
case Array arr:
27+
Console.WriteLine($"An array with {arr.Length} elements.");
28+
break;
29+
case IEnumerable<int> ieInt:
30+
Console.WriteLine($"Average: {ieInt.Average(s => s)}");
31+
break;
32+
case IList list:
33+
Console.WriteLine($"{list.Count} items");
34+
break;
35+
case IEnumerable ie:
36+
string result = "";
37+
foreach (var e in ie)
38+
result += "${e} ";
39+
Console.WriteLine(result);
40+
break;
41+
case object o:
42+
Console.WriteLine($"A instance of type {o.GetType().Name}");
43+
break;
44+
default:
45+
Console.WriteLine("Null passed to this method.");
46+
break;
47+
}
48+
}
49+
}
50+
// The example displays the following output:
51+
// An array with 5 elements.
52+
// 4 items
53+
// Null passed to this method.
54+
// </Snippet1>
55+
56+

0 commit comments

Comments
 (0)