I found a simple bug in VB.NET that can be easily reproduced:
Dim pDate As Date?
Dim pString As String = ""
' works fine as expected
pDate = If(False, "", Nothing)
' expected: pDate will be set to Nothing.
' BUG: Conversion from string "" to type 'Date' is not valid.
pDate = If(False, pString, Nothing)
'These both fail with the same error
pDate = pString
Dim pDate2 As Date? = ""
Question: Is this a bug? Or is there something wrong with me or my PC?
If this is a bug, is there a bug report of this (I cant seem to find it)?
Lessons learned:
- this is not a bug
- nullable date accepts object nothing
- nullable date rejects string nothing
pDate = Nothing ' ok. nullable date accepts object nothing
pString = Nothing
pDate = pString ' error. nullable date rejects string nothing
The bug is in your first use of
If(), not the second. Contrary to your comment, the result there is not “expected”. That call should fail, because “” cannot convert to a date and the ternary operator is typesafe at all levels whether or not the expression is used.I suspect it succeeds because of a compiler optimization: since everything is all literals, the condition is optimized away. It’s harder to make the optimization the second time, because the pString variable might be changed by another thread the compiler doesn’t know about yet.
Someone who’s handier with IL can probably confirm this.
The real surprise for me is that this is not caught until runtime. I would expect the compiler to notice the type mismatch and complain at that level, rather than waiting until execution. Your VB Option settings may have something to do with that.