C# Nullable DateTime

DateTime

A nullable DateTime can be null. The DateTime struct itself does not provide a null option. But the "DateTime?" nullable type allows you to assign the null literal to the DateTime type. It provides another level of indirection.

NullDateTime

Example

First, this program uses a nullable DateTime instance in various ways. A nullable DateTime is most easily specified using the question mark syntax, which results in the type "DateTime?".

Tip:A "DateTime?" is a struct that wraps a DateTime struct, providing another level of indirection that can simplify some programs.

Program that uses null DateTime struct: C#

using System;

class Program
{
    static void Main()
    {
	//
	// Declare a nullable DateTime instance and assign to null.
	// ... Change the DateTime and use the Test method (below).
	//
	DateTime? value = null;
	Test(value);
	value = DateTime.Now;
	Test(value);
	value = DateTime.Now.AddDays(1);
	Test(value);
	//
	// You can use the GetValueOrDefault method on nulls.
	//
	value = null;
	Console.WriteLine(value.GetValueOrDefault());
    }

    static void Test(DateTime? value)
    {
	//
	// This method uses the HasValue property.
	// ... If there is no value, the number zero is written.
	//
	if (value.HasValue)
	{
	    Console.WriteLine(value.Value);
	}
	else
	{
	    Console.WriteLine(0);
	}
    }
}

Output

0
9/29/2009 9:56:21 AM
9/30/2009 9:56:21 AM
1/1/0001 12:00:00 AM
Question and answer

This program introduces two methods: Main, and the Test method that uses the nullable "DateTime?" as a parameter. The "DateTime?" variable is first declared in the Main method body. It is passed as a parameter to the Test method.

Then:The "DateTime?" variable is reassigned to different values, including DateTime.Now, and tomorrow's date is computed.

The HasValue instance method is available on any nullable type. It returns true if the nullable type is logically non-null, and false if the null field on the nullable type is activated.

Also:The GetValueOrDefault method will return DateTime.MinValue for a null DateTime.

Null

Null keyword

We describe the differences between the "DateTime?" type and the DateTime struct, which can be wrapped by the nullable type. The "DateTime?" type has special semantics that allow you to use it as null, but it is a value type struct.

Note:The DateTime type has no way to be null because it is a value type and stored in the memory location of the variable itself.

DateTime.MinValue: Null

Summary

We looked at the nullable DateTime type in the C# language. We can specify a trailing question mark to transform the DateTime struct to a nullable DateTime struct wrapper. This adds utility for handling null and invalid data.


C#: Time