Nullable Types in C# with Examples

In C #, the compiler does not allow you to assign a null value to a variable. Therefore, C # 2.0 provides special functions for assigning a null value to a variable known as a Nullable type. With help of nullable, we can assign a null value to a variable. Types that accept Null values ​​introduced in C # 2.0 can only work with a value type, not a reference type.

Null acceptance types for a reference type are introduced later in C # 8.0 in 2019 so that we can explicitly define whether a reference type can contain a null value. This helped us fix the NullReferenceException problem without using any conditions. This article describes null-possible types for value types.

The Nullable type is an instance of the System. Nullable structure. Here is a T type that contains value types that cannot be allowed, such as an integer, a floating-point type, a Boolean type, and so on. For example, in a null integer type, you can store values ​​between -2147483648 and 2147483647 or a null value.

Syntax:

Nullable<data_type> name = null;

Example:

        Nullable<int> num = null;
        Console.WriteLine(num.GetValueOrDefault());
        int? num1 = null;
        Console.WriteLine(num1.GetValueOrDefault());

Output:

0
0

Characteristics of Nullable types

  • Using the nullable type, you can specify a zero value for a variable without creating a nullable type based on the reference type.
  • For nullable types, we can also assign values ​​for nullable.
  • You can use the Nullable.HasValue and Nullable.Value values.
  • We can use ! or == with nullable values

Null Coalescing Operator (??)

A null coalescing operator, in C #, is an operator used to check whether the value of a variable is zero. In  C# null coalescing operator is denoted by the symbol "??".

Syntax:

a ?? b

In the above syntax, a is the right operand and b is the left operand in the coalescing operator.

Some Important Points to remember about the null coalescing operator.

  • For the purpose of checking the null value, we used the null coalescing operator in c# and you can also assign a default value to a variable whose value is null(or nullable type).
  • we can not overload the null coalescing operator
  • It is right-associative.
  • we can use throw expression as a right-hand operand of the null coalescing operator which makes your code more concise.
  • In reference type and value type we can use the null coalescing operator

Example:

            int? a = null;
            int? b = 100;
            int? c = a ?? b;
            Console.WriteLine("Value of c is: {0} ", c);

Output:

Value of c is: 100