Why can you assign Nothing to an Integer in VB.NET?

后端 未结 5 1008
星月不相逢
星月不相逢 2021-01-17 07:22

Why am I allowed to assign Nothing to a value-type in VB.NET:

Dim x as Integer = Nothing

But I\'m not allowed to assign

5条回答
  •  旧巷少年郎
    2021-01-17 07:53

    An interesting example from the language spec: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=01eee123-f68c-4227-9274-97a13d7cb433&displaylang=en

    7.1.1 Nullable Value Types For value types, a ? modifier can be added to a type name to represent the nullable version of that type. A nullable value type can contain the same values as the non-nullable version of the type as well as the null value. Thus, for a nullable value type, assigning Nothing to a variable of the type sets the value of the variable to the null value, not the zero value of the value type. For example:

    Dim x As Integer = Nothing
    Dim y As Integer? = Nothing
    
    ' Prints zero
    Console.WriteLine(x)
    ' Prints nothing (because the value of y is the null value)
    Console.WriteLine(y)
    

提交回复
热议问题