
Every reference and value type has a default value. This value is returned by the default(Type) expression in the C# language. Default is most useful for writing generic classes. It also helps us understand better the language's type system.
KeywordsThis C# program demonstrates the default operator. Default returns the default value of a type.

In this first example, we look at four uses of the default expression in the C# language. The four types we apply the default expression to are the StringBuilder, int, bool, and Program types. The Program type is declared in the program itself. Finally, the values that were assigned are printed to the screen. The null value is printed as a blank line.
StringBuilder Secrets Int Type Bool Type Null TipsProgram that uses default expression [C#]
using System;
using System.Text;
class Program
{
static void Main()
{
// Acquire the default values for these types and assign to a variable.
StringBuilder variable1 = default(StringBuilder);
int variable2 = default(int);
bool variable3 = default(bool);
Program variable4 = default(Program);
// Write the values.
Console.WriteLine(variable1); // Null
Console.WriteLine(variable2); // 0
Console.WriteLine(variable3); // False
Console.WriteLine(variable4); // Null
}
}
Output
(Blank)
0
False
(Blank)
At the level of the intermediate language instructions, the default value expression is implemented using static analysis, meaning the default expressions are evaluated at compile time, resulting in no performance loss. In other words, no reflection to the type system or metadata relational database is used at runtime.
Intermediate Language
We looked at the default value expression in the C# programming language. The ECMA-344 specification describes this expression in chapter 14 and page 187. By understanding the usage of the default value expression, we can better understand the type system used in the C# language.
Reflection