Default value expressions

C# CONCEPTS

A default expression returns the default value of a type.

Learning Objectives

The article demonstrates how to use

  1. Default Operator

  2. Default Literal

Prerequisites

  1. Experience in basic concepts of C#.

  2. 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:

  1. Variable assignment or initialization.

  2. 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

Stay tuned on C#

View at Medium.com

#Csharp #DotnetCore #Coding #Dotnet #Programming

Recent Posts

See All

Design Pattern – Adapter

#Aspnetcore #AdapterDesignPattern #Csharp #DesignPatterns #Dotnet According to Gang of Four, the Adapter Pattern converts the interfaces of a class into interfaces that the client requires. In other w