Question

This might be more of a general question, but I hope this is the right place to ask. I'm not new to writing code, but somewhat new to VB.net. My background is not in computer science, so what I do know I know from the few classes I've taken, my own personal interest, and professional needs.

What I'm wondering is what the technical difference is between a variable like a string:

Dim myString As String

and a variable like a collection which must be instantiated:

Dim myCollection As Collection
myCollection = New Collection

I realize the latter is an object, but what I'm not sure I understand is why both the former and the latter aren't implemented in the same manner when neither require references outside of Visual Basic?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top