开发者

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

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

Dim x as Integer = Nothing

But I'm not 开发者_StackOverflow社区allowed to assign null in C#:

int x = null;


When you assign Nothing to a value type in VB.Net it instantiates that type with its default value. So in this case you're not creating a null integer, but an integer that holds the default value of 0


The equivalent C# code looks like this:

int x;
x = default(int);

Note that for reference types, the same still holds:

Dim y As Object
y = Nothing

That VB.Net code would look like this if mapped directly to C#:

object y;
y = default(object);

It's just a nice thing that the default for object (or any other reference type) in .Net is null. So we see that VB.Net's Nothing is not a direct analog to C#'s null, at least when used with value types.


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)


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.


Here's an interesting article about VB.NET and Nothing vs. Null. A small excerpt:


...value types, can’t be compared to Nothing or Null. Value types are types such as Integers and Bytes. From the Visual Basic Language Reference:

A value type cannot hold a value of Nothing and reverts to its default value if you assign Nothing to it. If you supply a value type in Expression, IsNothing always returns False.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜