C# CONCEPTS
A default expression returns the default value of a type.
Learning Objectives
The article demonstrates how to use
Default Operator
Default Literal
Prerequisites
Experience in basic concepts of C#.
Install latest visual studio community edition.
Getting Started
Default Operator
The default operator accepts only the name of a type or a type parameter.
Example
Console.WriteLine(default(int)); // output: 0 Console.WriteLine(default(object) is null); // output: True
Example with Generics
void DisplayDefaultOf<T>() { var val = default(T); Console.WriteLine($"Default value is {(val == null ? "null" : val.ToString())}."); }
DisplayDefaultOf<int?>(); DisplayDefaultOf<System.Numerics.Complex>();
// Output// Default value of System.Nullable`1[System.Int32] is null. // Default value of System.Numerics.Complex is (0, 0).
Default Literal
When the compiler infers the expression type, the default literal helps produce the type T’s default value.
Default literal is used in any of the following cases:
Variable assignment or initialization.
Declaration of default value for optional fields.
The usage of the default literal is shown in the following example:
T[] InitializeArray<T>(int length, T initialValue = default){ var array = new T[length]; for (var i = 0; i < length; i++) { array[i] = initialValue; } return array;}
void Display<T>(T[] values) => Console.WriteLine($"[ {string.Join(", ", values)} ]");
Display(InitializeArray<int>(3)); Display(InitializeArray<bool>(4, default));
// Output// [ 0, 0, 0 ]// [ False, False, False, False ]
Thank you for reading, and I hope you liked the article. Follow me on LinkedIn Instagram Facebook Twitter