devxlogo

Misconceptions on variables and binding

Misconceptions on variables and binding

Consider this line of code:

Dim x as Project1.Class1

Many developers think that we were declaring x as a “Project1.Class1” object. This is wrong. All object variables in VB are interface variables. In this line of code x is declared as the _Class1 interface defined in the Project1 Type library (the underscore is hidden by the kindness of the VB team). Note that in the above line of code you have not made any assumption regarding what object will provide an implementation of the Project1.Class1 interface. You create the actual object only later:

Set x = CreateObject("Project1.Class1") 'ORSet x = New Project1.Class1 'OR

One thing to stress: these 2 lines of codes are totally equivalent regarding early or late binding. There is a common misunderstanding among VB developers. They think that if you use the New keyword you are early-binding and that if you use CreateObject you are late-binding. Again, this is uncorrect. if you want to late-bind to the Project1.Class1 interface (that is use its Dispinterface counterpart) you should have written:

Dim x as Object  ' read Object as Dispatch

The confusion arises from the fact that VB hides you from most of the details of interface and classes definition.

– In the line [Dim x as Project1.Class1] Project1.Class1 is an interface indentifier (IID)
– In the line [Set x = New Project1.Class1] Project1.Class1 is a class identifier (The class CLSID)
– In the line [Set x = CreateObject(“Project1.Class1”)] “Project1.Class1” is the ProgId of the class, the ProgId is the human-readable name of the class that is mapped to the CLSID. This mapping is stored in the registry when you register your COM component (e.g. running regsvr32.exe if the component is a dll).

See also  Why ChatGPT Is So Important Today

If you create an object via the New keyword, the CLSID is read from the referenced component type library at build time and hardcoded in your component. If you use CreateObject VB queries the registry at run-time the map the ProgId to the CLSID (The CLSID is what you have to pass to the COM run-time when you ask it to create an object). As you may know you can even write:

Dim x as New Project1.Class1

In this case [Project1.Class1] is a class identifier. You are asking VB to create the Project1.Class1 class, ask to the object its default interface and place it into the x variable.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist