Visual Basic Concepts

How Object Creation Works in Visual Basic Components

See Also

In certain circumstances, the mechanism you use to create objects — that is, CreateObject, the New operator, or a variable declared As New — can have subtle effects on object creation. These effects depend on whether or not Visual Basic uses the object creation services provided by the Component Object Model (COM).

When you create objects from classes that are provided by other components, Visual Basic always uses COM object creation services. As a result, when you’re creating externally provided objects, there are no differences between the New operator, declaring a variable As New, and using the CreateObject function.

The CreateObject function always uses COM object creation services, whether you use it to create externally provided objects or to create instances of classes that are part of your project. So for CreateObject, there's no difference between external and internal object creation.

However, when you use the New operator (or a variable declared As New) to create an instance of a class that's part of your project, Visual Basic uses a very efficient private implementation of COM object creation.

In other words, Visual Basic uses the same mechanism for all object creation except creating objects with New or As New from classes in your project. This is summarized in the following table.

Object created from Using CreateObject Using New, As New
A class provided by another component COM object creation services COM object creation services
A class that’s part of your project COM object creation services Visual Basic private object creation

Note   The CreateObject function cannot be used on classes whose Instancing property is Private or PublicNotCreatable. The New operator can be used on any class.

The following are specific examples of the subtle differences that can arise depending on how you create objects from classes that are part of your project: