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# ?
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# ?
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.
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.