The following compiles in VB.NET (with Option Strict On) and outputs False:
Dim b As Boolean? = Nothing
Dim myString = If(b, "True", "False")
Why does that work?
-
The documentation clearly states that the three-argument version of
Ifrequires aBooleanas the first parameter:argument1 Required. Boolean. Determines which of the other arguments to evaluate and return.
-
and there is no implicit conversion from
Boolean?toBoolean:Dim b1 As Boolean? = Nothing Dim b2 As Boolean = b1 ' Fails with the following error: ' Option Strict On disallows implicit conversions ' from 'Boolean?' to 'Boolean'.
So, why does this work? Is it a bug (or “hidden feature”) in the compiler or is it a bug in the documentation and Boolean? is actually a valid type for the first argument of If(a, b, c)?
PS: In C#, b ? x : y does not compile if b is of type bool?.
EDIT: I’ve reported this issue to Microsoft Connect. Someone from MS has replied and confirmed that the documentation will be updated to include the Boolean? case.
There’s two “why’s”. Why does it and why did they do it that way. I can answer the first, the second is Microsoft’s.
If you inspect the code generated from VB.Net using Reflector you’ll see this:
Or C#:
So the compiler itself is inserting the
GetValueOrDefaultfor theNullable(of T)