Skip to content

Commit e9c1133

Browse files
pkulikovRon Petrusha
authored andcommitted
Added the default operator snippets (#1132)
1 parent 0c47594 commit e9c1133

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
using System;
2+
3+
namespace operators
4+
{
5+
public static class DefaultOperator
6+
{
7+
public static void Examples()
8+
{
9+
WithOperand();
10+
DefaultLiteral();
11+
}
12+
13+
private static void WithOperand()
14+
{
15+
// <SnippetWithOperand>
16+
Console.WriteLine(default(int)); // output: 0
17+
Console.WriteLine(default(object) is null); // output: True
18+
19+
void DisplayDefaultOf<T>()
20+
{
21+
var val = default(T);
22+
Console.WriteLine($"Default value of {typeof(T)} is {(val == null ? "null" : val.ToString())}.");
23+
}
24+
25+
DisplayDefaultOf<int?>();
26+
DisplayDefaultOf<System.Numerics.Complex>();
27+
DisplayDefaultOf<System.Collections.Generic.List<int>>();
28+
// Output:
29+
// Default value of System.Nullable`1[System.Int32] is null.
30+
// Default value of System.Numerics.Complex is (0, 0).
31+
// Default value of System.Collections.Generic.List`1[System.Int32] is null.
32+
// </SnippetWithOperand>
33+
}
34+
35+
private static void DefaultLiteral()
36+
{
37+
// <SnippetDefaultLiteral>
38+
T[] InitializeArray<T>(int length, T initialValue = default)
39+
{
40+
if (length < 0)
41+
{
42+
return default;
43+
}
44+
45+
var array = new T[length];
46+
for (var i = 0; i < length; i++)
47+
{
48+
array[i] = initialValue;
49+
}
50+
return array;
51+
}
52+
53+
void Display<T>(T[] values) => Console.WriteLine($"[ {string.Join(", ", values)} ]");
54+
55+
Display(InitializeArray<int>(3)); // output: [ 0, 0, 0 ]
56+
Display(InitializeArray<bool>(4, default)); // output: [ False, False, False, False ]
57+
58+
System.Numerics.Complex fillValue = default;
59+
Display(InitializeArray(3, fillValue)); // output: [ (0, 0), (0, 0), (0, 0) ]
60+
// </SnippetDefaultLiteral>
61+
}
62+
}
63+
}

csharp/language-reference/operators/Program.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,10 @@ static void Main(string[] args)
6262
LambdaOperator.Examples();
6363
Console.WriteLine();
6464

65+
Console.WriteLine("=========== default operator examples ==========");
66+
DefaultOperator.Examples();
67+
Console.WriteLine();
68+
6569
Console.WriteLine("========== delegate operator examples ==========");
6670
DelegateOperator.Examples();
6771
Console.WriteLine();

0 commit comments

Comments
 (0)