We all know that VB\'s Nothing
is similar, but not equivalent, to C#\'s null
. (If you are not aware of that, have a look at this answer first.)
The simple answer is, no. There is no expression in VB.NET that only returns null
. As you know, when the compiler parses a command using ternary operator, it infers the output type based on the two inputs. If one of the two inputs is Nothing
, it must rely solely on the other parameter. Therefore, the "right" way to do it in VB.NET is to first cast the other parameter to Object
, thereby forcing the output of the operation to be an Object
:
Dim o As Object = If(myBool, DirectCast(5, Object), Nothing)
If, however, you really need an in-line expression which, itself, always evaluates to null
, you could always do it by invoking a lambda expression, like this:
Dim o As Object = If(myBool, 5.0, (Function() Nothing).Invoke())
That syntax should work in any situation and would always result in Nothing
rather than potentially resulting in default value.