C# Nullable Datetime


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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 23-Jun-2020

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements