tags:

views:

281

answers:

3

Why am I allowed to say:

Dim x as Integer
x = Nothing

in VB.NET, but I can't say:

int x;
x = null;

in C# ?

A: 

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.

M4N
I know that, but that is not the question I'm asking... neither example in my question (C# or VB.NET) is using nullable types
JoelFan
+12  A: 

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

Joey
So it's like: x = default(int) in C# ?
JoelFan
@JoelFan : Yes.
BlueRaja - Danny Pflughoeft
Surely it's like `int x;`
Chris S
From the VB.NET Language Reference: "Assigning Nothing to a variable sets it to the default value for its declared type. If that type contains variable members, they are all set to their default values" ... "If the variable is of a reference type — that is, an object variable — Nothing means the variable is not associated with any object."
Michael Burr
@JoelFanYou nailed it, the c# equivalent of vb's "i = Nothing" is "i = default(Int32)". Any value type (is defined as a struct opposed to a class) will get the appropriate default value and any reference type will become null.
Eric Tuttleman
@Eric, so in the general case, it would be like: x = default(x.GetType())
JoelFan
@Chris, don't call me surely
JoelFan
@JoelFan In spirit, but it's a compile-time thing, so you can't use a run-time method like GetType. That's why you're always seeing people using exmaples like defualt(String).
Eric Tuttleman
+3  A: 

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.

Joel Coehoorn
Not sure about mapping, because VB.NET code has explicit type indication: `Int`. However, code like `Dim X = Nothing` is what you wrote underneath.
abatishchev