devxlogo

Never use New to create MTS/COM+ objects

Never use New to create MTS/COM+ objects

A common question among VB developers is: Why is it dangerous the use of the New keyword in VB to create COM objects registered under MTS/COM+?

The New keyword is the only way to go when you want to create objects that are defined as PublicNotCreatable or Private (CreateObject doesn’t work) inside the same component as the calling code. As you know VB lets you use New to create Multiuse classes as well. Unfortunately the New keyword has a couple of drawbacks:

1) In situations where the caller and the callee are in the same EXE/DLL COM component VB perform an internal creation of the COM object bypassing the COM run-time (and the MTS run-time if the object is registered under MTS). While this fact is not a problem under a non-MTS environment, the situation gets very dangerous under MTS and COM+. What happens is that, since MTS/COM+ is not notified of the object creation, the newly created object gets access to the ObjectContext of the father and MTS sees the code running inside method calls of the child object as “inline-code” of the father. I leave as an exercise to the reader what can happen if the child object calls SetComplete (against the ObjectContext of the father).

2) When you declare an object (Interface) with the syntax

Dim x As New MyClass

VB checks every time the object is referenced in the code. If it is Nothing, VB silently (re)creates it (This means you’ll never get a “object variable or with block not set” error). If you are not aware of this your code could follow unexpected execution paths.

See also  Why ChatGPT Is So Important Today

 

Public sub DoWork()        Dim X as New MyClass   ' MyClass is registered as "requires transaction"  x.dosomemorework       ' VB creates it, the component ball start spinning in                          ' the MTS explorer, the transaction start  Set x = Nothing        ' The ball stop spinning  If x Is Nothing Then   ' VB recreates it, the ball start spinning again, the                          ' transaction start again      Format Drive C     '  this code will never be executed  End If       ' From here to when x goes out of scope x is activated   ' (and probably you don't know this).  End Sub    
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