VB.NET and If Nullable Weirdness
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 IfAs expected, this outputs “Date is null”:
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 IfAnd then run the app, things get interesting:
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:
Solution to the issue is to use new DateTime? instead of Nothing:
The following StackOverflow question contains more info about why this is happening.



