What is the difference between:
Dim intVal as integer
intVal = 0
and
intVal = nothing
I have read from MSDN that nothing sets a value to 0 as well:
From MSDN:
Public Structure testStruct
Public name As String
Public number As Short
End Structure
Dim ts As testStruct, i As Integer, b As Boolean
ts = Nothing
' The preceding statement sets ts.name to "" and ts.number to 0.
i = Nothing
b = Nothing
' The preceding statements set i to 0 and b to False.
Nothing is sometimes confused with Null, but they are very different concepts because Nothing means absence of anything, while Null means unknown (you do not know if there is a thing or not).
null means that a variable contains a reference to a space in memory that does not contain an object. 0 is a numeric data type with a value of 0.
In order to define a null variable, you can use the None keyword. Note: The None keyword refers to a variable or object that is empty or has no value.
In programming a variable is simply a place to store data. A variable has a name and a data type. In Visual Basic .NET, a variable is declared using the Dim (short for Dimension) statement. Here is the syntax: Dim varName As varType.
Nothing is usually used for object references, if you assign it to a value type it initialize it with the default value. In .NET world, default values are simply a block of memory full of zeroes. So, an integer assigned to nothing will be 0, a struct assigned to nothing will be a structure filled of zeroes.
A null reference is a special reference, it means, no reference, and is expressed, indeed, as a pointer with all zeroes.
In C# you can use the default(TYPE)
to obtain the same result, it is used to assign zero to whatever you want.
String are references type, like object, so strings will not be assigned to "" but to Nothing, strings are not value types.
Dim s as String
s = Nothing
Console.WriteLine Object.ReferenceEquals(s, Nothing) ' Will print true
Console.WriteLine Object.ReferenceEquals(s, "") ' Will print false
Strings are still reference types, so when you assign it to Nothing you will set the reference to zero.
In .Net an Integer is a value type and therefore cannot be null.
If you create a variable of type integer and don't assign it, it will be 0 because of the way the language works.
It's not hyperbole to say that some of the most irritating/prevalent bugs in modern computing have been caused by un-initialised variables so the .Net team made the decision to ensure that all value types don't suffer from that problem.
It is bad practise though to assume that the compiler/JIT will resolve these variables to a known value such as 0 for integers or False for booleans, so you should always use your first example.
But to answer your question clearly, there is no difference, but it's best to use the first example.
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