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 null
in C#:
int x = null;
Nothing represents the default value of a data type. The default value depends on whether the variable is of a value type or of a reference type. A variable of a value type directly contains its value. Value types include all numeric data types, Boolean , Char , Date , all structures, and all enumerations.
Integers cannot be set to Null. You have to make the integer "nullable" by adding a question mark after the word Integer.
VB.Net IsNothing Function returns a Boolean value indicating whether an expression has no object assigned to it. There is no direct, 100% equivalent of the Vb.Net function IsNothing, but the test against null accomplishes the same thing.
In Visual Basic 6.0, the Null keyword indicated that a field contained no valid data, and the IsNull function was used to test for Null. In addition, Visual Basic 6 supported Null propagation when Null was used in an expression, the result of the expression would also be 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With