Search code examples
vb.netinterfacenullableimplicit-conversion

Implicit Interface casts of Nullables


With VB's Option Strict On, why does a Nullable(Of T) not require an explicit cast to an interface of T when it does require one to T?

I.e.

Dim x As Integer? = 5
Dim y As Integer
Dim z As IComparable

y = x ' Fails to compile with error
      ' "Option Strict On disallows implicit conversions from 'Integer?' to 'Integer'."
z = x ' Succeeds

EDIT: As (sort of) shown by @SSS, part of the answer is that Nullable values are, well, nullable, and can be Nothing, which is fine for a reference like an interface. So this conversion will always succeed, unlike the conversion to T case (which fails when the Nullable has no value), and so it can be seen as an implicit conversion.

My question now becomes "how?". How is the conversion from a Nullable(Of T) (which has no interfaces of its own) to an interface of T theoretically negotiated?

I know the implementation is box Nullable<T>, which effectively strips the Nullable wrapper, but I'm confirming the concept here...

(So I'll review the documentation and see if they explain this.)


Solution

  • Without actually reading documentation yet, I'm going to attempt an answer:

    Firstly, the higher-level answer is that casting a Nullable to an interface is "safe" and will not throw, so it is logically a Widening operator and should not need to be explicit (compared to casting to T, when .HasValue is False it throws, so it should not be implicit with Option Strict On).

    However, technically the "how" is a bit obscure: Even though some of the behaviour of Nullable is encoded in the metadata available via reflection, much of its "magic" is hidden in:

    • the runtime behaviour of box on a Nullable (and thus the compiler knows when to leave "lifting" to that), and
    • the other points made by Eric Lippert in his answer for C# and their equivalent in VB.NET.

    It looks like S. Somasegar's blog post announcing changes to Nullable support in a late beta release for VS2k5 is also relevant here.