Heinzi Heinzi - 7 months ago 11
Vb.net Question

Is there a VB.NET expression that *always* yields null?

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.)

Just out of curiosity, I'd like to know the following:

Is there a VB.NET expression that always yields
null
?





To give a concrete example, take the following statement:

Dim o As Object = If(myBool, 5, ...)


Is it possible to replace
...
with something, such that
o
is
5
when
myBool
is true and
Nothing/null
when
myBool
is false?

Obvious solutions that won't work:


  • Nothing
    (see the question to the linked answer above),

  • DirectCast(Nothing, Object)
    (throws a compile-time error with Option Strict On),

  • DirectCast(Nothing, Integer?)
    works for this example, but does not work in general (if you replace
    5
    with
    5.0
    in this example, you'd need to modify the cast).



Obvious workarounds (won't count as answers):


  • Declare an
    Object
    variable or field, set it to
    Nothing
    and use that for
    ...
    ,

  • define a method or property that always returns
    Nothing
    ,

  • DirectCast
    the second parameter (
    5
    ) to
    Object
    .



Note: The example above is just an example. The question itself is written in bold.

Answer

The first answer I gave missed some points, but this should do it:

Dim o As Object = If(myBool, 5, DirectCast(Nullable.GetUnderlyingType(GetType(Integer)), Object))

This uses the fact that Nullable.GetUnderlyingType will return a null reference if you pass it a type which isn't a nullable value type - which Integer isn't. Other alternatives exist, such as Type.GetElementType(), or perhaps GetType(Object).BaseType.

I've checked that this works with multiple different types for the second operand.

It's slightly annoying that you have to cast to Object... I'm still working on alternatives for that...

Comments