The answer is different for VBA and VB.NET.
Actually, in VB.NET, you do need to instantiate a String
. For instance, the following code throws and exception in VB.NET:
Dim s As String
Dim same As Boolean = s.Equals("") ' Throws NullReferenceException
The reason it throws an exception is because you are trying to call the Equals
method on using a variable which is not currently referencing (pointing to) any object. In other words, the s
variable is currently null (Nothing
in VB). To fix it, you'd need to instantiate an object, like this:
Dim s As String = ""
Dim same As Boolean = s.Equals("") ' Works (same = True)
However, your question is still valid because you don't need to instantiate some types of variables such as Integer
:
Dim i As Integer
Dim same As Boolean = i.Equals(0) ' Works (same = True)
The different between the two is that String
is a Reference Type (a Class
) whereas Integer
is a Value Type (a Structure
). You can read more about the difference on the MSDN here.
In VBA, the difference is similar, a bit more murky. VBA has a set of core primitive data types which do not require instantiation (like value types in .NET), and everything else is considered an Object
, which does require instantiation (like reference types in .NET). Also, VBA allows you create Structure
types which are treated like primitive types in that you do not instantiate them.
To further complicate things, in VBA, String
is a primitave data type, but in VB.NET it is a reference type.