English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# Nullable Types (Nullable)

It is well known that null values cannot be assigned to value types. For example,int i = null will throw a compile-time error.

c# 2.0 introduced nullable types, allowing you to assign null to value type variables. You can use Nullable<t> to declare nullable types, where T is a type.

Nullable type definition

Nullable<int> i = null;

Nullable types can represent the correct value range of their underlying value types, plus an additional null value. For example, Nullable<int> can allocate from -2147483648 to 2147483647 or a null value.

The Nullable type is an instance of System.Nullable<t> struct.

[Serializable]
public struct Nullable<T> where T : struct
{        
    public bool HasValue { get; }
      
    public T Value { get; }
        
    // Other implementations
}

The nullable Int type is the same as the ordinary int type, with a flag indicating whether the int has a value (whether it is null)....The rest are compiler magic, which treats 'null' as a valid value.

static void Main(string[] args)
{
    Nullable<int> i = null;
    if (i.HasValue)
        Console.WriteLine(i.Value); // Or Console.WriteLine(i)
    else
        Console.WriteLine("Null");
}
Output:
Null

If the object has been assigned a value, it returns true; if no value has been assigned or a null value has been assigned, it returns false.

If the NullableType.value type is null or no value has been assigned, accessing the value using NullableType.value will throw a runtime exception. For example, if i is null, the value will throw an exception:

Invalid use of nullable types

If it is not null Use the GetValueOrDefault() method to get the actual value; if it is null, use the default value. For example:

static void Main(string[] args)
{
    Nullable<int> i = null;
    Console.WriteLine(i.GetValueOrDefault()); 
}

Shorthand syntax for nullable types

You can use the '?' operator to simplify the syntax, such as int ?, long? instead of using Nullable <T>.

int? i = null;
double? D = null;

Null coalescing operator (??)

Using the '??' operator, assign nullable types to non-nullable types.

int? i = null;
            
int j = i ?? 0;
Console.WriteLine(j);
Output:
0

In the above example, i is a nullable int, and if it is assigned to a non-nullable int j, if i is null, it will throw a runtime exception. Therefore, to reduce the risk of exceptions, we use the '??' operator, which assigns 0 to j if i is null.

using System;
namespace CalculatorApplication
{
   class NullablesAtShow
   {
         
      static void Main(string[] args)
      {
         
         double? num1 = null;
         double? num2 = 3.14157;
         double num3;
         num3 = num1 ?? 5.34;      // num1 If it is a null value, it returns 5.34
         Console.WriteLine("num3 Value: {0}3);
         num3 = num2 ?? 5.34;
         Console.WriteLine("num3 Value: {0}3);
         Console.ReadLine();
      }
   }
}

Output result:

num3 Value: 5.34
num3 Value: 3.14157

Assignment rules

The assignment rules for nullable types are the same as those for value types. If a nullable type is declared as a local variable in a function, it must be assigned a value before it is used. If it is a field of any class, it will have a default null value by default.

For example, declare and use the following nullable int without assigning any value. The compiler will output“Use unassigned local variable 'i'”Error:

Error: Unassigned nullable type error

In the following example, the nullable int type is a field of the class, so no error will occur.

class MyClass
{
    public Nullable<int> i;
}
class Program
{
    static void Main(string[] args)
    {
        MyClass mycls = new MyClass();
        if (mycls.i == null)
            Console.WriteLine("Null");
    }
}
Output:
Null

Nullable class comparison method

Null is considered less than any value. Therefore, comparison operators cannot be used with null. See the following example, where i is neither less than j, nor greater than j, nor equal to j:

static void Main(string[] args)
{
    int? i = null;
    int j = 10;
    if (i < j)
        Console.WriteLine("i < j");
    else if (i > 10)
        Console.WriteLine("i > j");
    else if (i == 10)
        Console.WriteLine("i == j");
    else
        Console.WriteLine("Cannot compare");
}
Output:
Cannot compare

The Nullable static class is an auxiliary class for the Nullable type. It provides comparison methods for comparing nullable types. It also has a GetUnderlyingType method that returns the base type parameter of the nullable type.

static void Main(string[] args)
{
    int? i = null;
    int j = 10;
    if (Nullable.Compare<int>(i, j) < 0)
        Console.WriteLine("i < j");
    else if (Nullable.Compare<int>(i, j) > 0)
        Console.WriteLine("i > j");
    else
        Console.WriteLine("i = j");
}
Output:
i < j

Characteristics of nullable types

  1. Nullable types can only be used with value types.

  2. If Value is null, the Value property will throw an InvalidOperationException; otherwise, it will return the value.

  3. If the variable contains a value, the HasValue property returns true; if it is null, it returns false.

  4. Only the == and != operators can be used with nullable types. For other comparisons, please use the Nullable static class.

  5. Nested nullable types are not allowed. Nullable <Nullable <int>> i; will result in a compile-time error.

 Key Points to Remember

  1. The Nullable <T> type allows null to be assigned to value types.

  2. ?The operator is a shorthand syntax for the Nullable type.

  3. Use the value property to get the value of a nullable type.

  4. UseHasValueProperty checks whether a value is assigned toCanEmpty Type.

  5. The static Nullable class is a helper class used to compare nullable types.