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") 'OR
Set 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).
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:
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.
Dim x as New Project1.Class1
This tip is taken from the FAQ list that Enrico mantains at his own home page (www.sabbasoft.com/mts_faq.htm).