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
+ }
0 commit comments