0 Comments

Recently I blogged about the VB.NET String Concatenation Weirdness. That’s not the only thing which can hit you if you mainly code in C#. Here’s an another example, as pointed out by my co-worker Panu Oksala. This time the weirdness is related to If and nullable fields.

Here’s some simple code:

        Dim myDate As DateTime?

        myDate = Nothing

        If (myDate Is Nothing) Then
            Console.WriteLine("Date is null")
        Else
            Console.WriteLine(myDate)
        End If

As expected, this outputs “Date is null”:

image

But, if we include If-statement in the myDate-assignment:

        Dim myDate As DateTime?

        myDate = If(True, Nothing, DateTime.Today)

        If (myDate Is Nothing) Then
            Console.WriteLine("Date is null")
        Else
            Console.WriteLine(myDate)
        End If

And then run the app, things get interesting:

image

So, we’re not getting “Date is null”. And we’re not getting the other if-option which is DateTime.Today. Instead, myDate is initialized as DateTime.MinValue:

image

Solution to the issue is to use new DateTime? instead of Nothing:

image

The following StackOverflow question contains more info about why this is happening.