Concept Flow - Default values for types
Declare variable
Assign default value
Use variable
Output default value
When you declare a variable without assigning a value, C# gives it a default value based on its type automatically.
int number;
bool flag;
string text;
Console.WriteLine(number);
Console.WriteLine(flag);
Console.WriteLine(text);| Step | Action | Variable | Value | Output |
|---|---|---|---|---|
| 1 | Declare int number | number | 0 (default) | |
| 2 | Declare bool flag | flag | false (default) | |
| 3 | Declare string text | text | null (default) | |
| 4 | Print number | number | 0 | 0 |
| 5 | Print flag | flag | false | False |
| 6 | Print text | text | null |
| Variable | Start | After Declaration | Final |
|---|---|---|---|
| number | undefined | 0 | 0 |
| flag | undefined | false | false |
| text | undefined | null | null |
Default values in C#: - int defaults to 0 - bool defaults to false - string (reference type) defaults to null Variables get these values automatically when declared without assignment. Use Console.WriteLine to see these defaults.
int type variable in C#?int have a default value of zero when not initialized.intint is 0, not null or any other value.T in C#?T is default(T).T.default(), default = T, and T.default are invalid syntax in C#.bool flag = default;
Console.WriteLine(flag);
bool in C# is false.flag is assigned default, so it holds false. Printing it outputs "False".string text = default;
int number = default;
Console.WriteLine(text.Length);
string, default is null.text.Length when text is null causes a NullReferenceException at runtime.struct Point { public int X; public int Y; }
Point p = default;
Console.WriteLine(p.X + "," + p.Y);default.X and Y are int, so default is 0 for each.p.X + "," + p.Y outputs "0,0".Pass the test and this pattern moves unknown