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

后端 未结 5 966
星月不相逢
星月不相逢 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

    About Nothing from the VB.NET specifications (v.10):

    Nothing is a special literal; it does not have a type and is convertible to all types in the type system, including type parameters. When converted to a particular type, it is the equivalent of the default value of that type.

    from C# specs (v4)

    The null-literal can be implicitly converted to a reference type or nullable type.

    So, C# null can't be implicitly converted to value types, but VB.NET Nothing can.

    However setting x = Nothing is confusing, because is not clear at first view that is equivalent to x = 0.

    Especially when Nothing is expected to be a invalid value and 0 - a valid one, this assignment can bring misunderstandings or even implicit bugs in the VB.NET code.

提交回复
热议问题