C# Nullable Datetime

CsharpProgrammingServer Side Programming

Using the DateTime nullable type, you can assign the null literal to the DateTime type.

A nullable DateTime is specified using the following question mark syntax.

DateTime?

The following is the code to implement Nullable Datetime.

Example

 Live Demo

using System;
class Program {
   static void Main() {
      DateTime? dt = null;
      DateFunc(dt);
      dt = DateTime.Now;
      DateFunc(dt);
      dt = null;
      Console.WriteLine(dt.GetValueOrDefault());
   }
   static void DateFunc(DateTime? dt) {
      if (dt.HasValue) {
         Console.WriteLine(dt.Value);
      } else {
         Console.WriteLine(0);
      }
   }
}

Output

0
9/17/2018 8:27:07 AM
1/1/0001 12:00:00 AM
raja
Published on 17-Sep-2018 16:07:35
Advertisements