A default literal expression in C# produces a default value for a type. This is achieved using the default
keyword, which previously had the following syntax:
dataType variableName = default(dataType);
In the above code, default
returns a default value for the given dataType
. However, with C# version 7.0 onward, the default
keyword does not take any argument; instead, it automatically infers the dataType
based on the dataType
of the variable its value is being assigned to.
Therefore, the syntax for default
in newer versions of C# is:
dataType variableName = default;
The following example depicts the usefulness of the default
keyword:
class HelloWorld {static bool Test(bool a = default) {return a;}static void Main() {int x = default;System.Console.WriteLine("Default 'int' value inside 'x':");System.Console.WriteLine(x);System.Console.WriteLine("Result of Test():");System.Console.WriteLine(Test());}}
Default 'int' value inside 'x':
0
Result of Test():
False
In the example above, the default
keyword is used to initialize the int
variable x
. The default value turns out to be 0
. Moreover, the default
keyword can also be used in function declaration as a default parameter.
The function Test
in line 2 is one such example. The argument a
is of type bool
. Since this argument is not supplied, the default
value is stored inside a
. Later on, in line 3 this default
value is returned and printed on the console.