Exposing .NET Classes to COM with the ComClass Attribute
|The ComClass attribute instructs the VB.NET compiler to handle most of the complexity involved in exposing your classes to COM.|
Exposing a managed class to COM by hand is a confusing process that requires a good deal of COM programming knowledge. To ease this process, you can use a tool called TLBEXP, which comes with the .NET Framework SDK, to expose your classes to COM. However, TLBEXP auto-generates class interfaces that include all public members in your class hierarchy, all the way to Object. This makes the interface rather susceptible to versioning issues, especially when any of the base classes change. TLBEXP also never generates event interfaces. As an easy alternative, the ComClass attribute instructs the VB.NET compiler to handle most of the complexity involved in exposing your classes to COM.
demonstrates how to use the ComClass attribute. Simply attach it to your public class and specify any optional GUIDs you would like used. The rest is taken care of for you. Listing 2
reveals what actually happens when you apply a ComClass attribute to your class. The details are beyond the scope of this article. However, what happens is that a class interface and event interface gets created and each of the corresponding members are decorated with the necessary attributes to specify DispIDs, default interfaces and GUIDs. TLBEXP then uses this information to build the correct COM description of your component.
Because the compiler performs all of this work for you, there is less complexity in your code and less opportunity for error. Just as with VB6, exposing your classes to COM is not a difficult process. Instead, you have more time to spend on the important things, like architecture and algorithms. (See Sidebar: Secrets of Debugging)
That Warm and Fuzzy Feeling
Visual Basic .NET is undeniably a departure from previous versions. From running on top of a new platform, to gaining full object-oriented status, the Visual Basic of the next millennium is somewhat different from days of yore. However, the focal point for all versions of Visual Basic, past, present and future is and will always be making you a better, more productive programmer.