Compartilhar via


Why Nullable cannot be passed to an “As Structure” type parameter.

Here is an interesting experiment:

Class cls1(Of T As Structure)

End Class

Module Module1

Sub Main()

Dim v As cls1(Of Nullable(Of Integer))

End Sub

End Module

We all know that Nullable(Of T) is a structure. However the code above gives a compile error:

'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.

It seems that Nullable is explicitely not allowed to be passed to a type parameter constrained to be a value type. Why? The reason is pretty simple. The purpose of Nullable is to add additional “No Value” state to value types. However it would be weird to allow to do this more than once.
Consider a value type Boolean – it can have 2 possible states:

   True, False

Nullable(Of Boolean) will have 3 states:

   True, False, “No Value”

How many states would  Nullable(of Nullable(of Boolean))  have? Well, since Nullable adds another “No Value” state it would have 3 states:

      True, False, “No Value”, “No Value”

Now this is very weird. Type with multiple “No Value” states seems just plain wrong. (Also consider cases with Nullable used more than once).

Hence it should be invalid to pass Nullable as a type argument to Nullable. Even more – to guarantee that we never get into Nullable(Of Nullable …) situation indirectly, compiler has to reject passing Nullable to any “As Structure” type parameter.