Nullable DateTime and 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 .

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  As Integer = Nothing

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

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

2 Responses

  1. Pingback: Nullable DateTime and Ternary Operator in C# | ProgramInDotnet

Leave a Reply