CSharp - Implicit and Explicit Nullable Conversions

Introduction

The conversion from T to T? is implicit, and from T? to T is explicit. For example:

int? x = 1;        // implicit
int y = (int)x;    // explicit

The explicit cast is equivalent to calling the nullable object's Value property.

an InvalidOperationException is thrown if HasValue is false.

Demo

using System;
class MainClass//from  ww  w .j a v a  2s  . c o m
{
   public static void Main(string[] args)
   {

        int? x = 1;        // implicit
        Console.WriteLine(x);
        
        int y = (int)x;    // explicit
        Console.WriteLine(y);
        
        x = null;
        Console.WriteLine(x);
        
        y = (int)x;    // explicit
        Console.WriteLine(y);

   }
}

Result