C# Tips & Tricks #31 – Nullable DateTime & Ternary Operator

This post will explain the different ways to assign the null values to the Nullable Datetime and explain how to use the ternary operator in C#.

Just Recently when I was working on a solution to assign Null values to the Datetime , I was struck up for some time in doing this though the solution was simple . I had to cast to the right type ( Nullable of Datetime ) .

The stuff that i was doing was assigning a value null directly to the variable when used with the Ternary or coascalence operator .

This post talks about the different ways of assigning the null value to the Nullable Datetime .

Using Nullable DateTime and Ternary Operator in C#

Here are some simple and traditional ways of doing it .

1. Use if statements

DateTime ? KaavalanReleaseDate = new DateTime();

if (String.IsNullOrEmpty("15.01.2011"))
{
     KaavalanReleaseDate = null;
}
else
{
     KaavalanReleaseDate = DateTime.Parse("15.01.2011");
}

Here we use the the Nullable Datetime which can take up the Null value .

2. Declaring a Nullable Variable

DateTime ? KaavalanReleaseDate = new DateTime();

Nullable<DateTime> NotReleasing = new Nullable<DateTime>();

if (String.IsNullOrEmpty("15.01.2011"))
{
     KaavalanReleaseDate = NotReleasing;
}
else
{
     KaavalanReleaseDate = DateTime.Parse("15.01.2010");
}

3. Use the Ternary Operator

Try this . Will it really work ?? .

DateTime ? KaavalanReleaseDate = new DateTime();

string ReleasingOn = "10.01.2011";

KaavalanReleaseDate = (ReleasingOn == null ? null : Convert.ToDateTime(ReleasingOn));

No .:(
Wait a minute in the example 1 we assigned null directly to  KaavalanReleaseDate , but when we do the same here , we get the following error message

” Type of conditional expression cannot be determined because there is no implicit conversion between ‘<null>’ and ‘System.DateTime’ “

The right way to get it work is this .

DateTime ? KaavalanReleaseDate = new DateTime();

string ReleasingOn = "15.01.2011";

KaavalanReleaseDate = (ReleasingOn == null ? (DateTime?)null : 

Convert.ToDateTime(ReleasingOn));

The Null and Datetime is somewhat not compatible and thus casting plays a important role .

Here’s a nice article on Nullable types and the ternary operator. Why won’t this work?

Note : try assinging a null value to an integer in c# and Nothing to an Integer in VB.NET like

int nullData = null;

Dim nullData&nbsp; As Integer = Nothing

One might a see a difference that in c# , it will throw a compile time error where as VB.NET doesnot .

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Hey, wait!Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.