Although in modern world applications this practice
is less frequent than in the past, you can expose .NET objects to the
COM world. For example, a VB 6 application can consume an object like
this. To demonstrate how you accomplish this export, create a new class
library and rename Class1.vb to Contact.vb. The first thing you need to
do to make a class consumable from COM is enable the COM
interoperability support. Now open My Project and then select the Compile tab. Flag the Register for COM Interop item at the bottom of the page, as shown in Figure 1.
This operation tells Visual
Studio that it needs to register the COM component on build and adds
the following line of code in AssemblyInfo.vb so that it makes it
visible to COM:
<Assembly: ComVisible(True)>
Any class that you want to
expose to COM has the following requirements: It must have a public,
empty, parameterless constructor, any member, including types, to be
exposed must be Public (no other modifiers are allowed), and it cannot include abstract classes. (This is just because they cannot be consumed.)
|
The ComVisible
attribute establishes the visibility level and granularity not only at
assembly level, but also for classes and class members. At the moment
implement the Contact class as follows:
Public Class COMContact
Public Property FirstName As String
Public Property LastName As String
Public Property Email As String
Public Property BirthDay As Date
Public Sub New()
End Sub
End Class
Now you can decide the visibility level for each member in the class by decorating the class and its members with the System.Runtime.InteropServices.ComVisible attribute. The following code demonstrates how to make COM-visible only some members from the Contact class:
Imports System.Runtime.InteropServices
<ComVisible(False)>
Public Class COMContact
<ComVisible(True)>
Public Property FirstName As String
<ComVisible(True)>
Public Property LastName As String
<ComVisible(True)>
Public Property Email As String
<ComVisible(False)>
Public Property BirthDay As Date
Public Sub New()
End Sub
End Class
The class is marked as ComVisible(False)
simply because not all its members are COM-visible. Notice that a
public, empty constructor is required for COM-visible objects.
The next step should be to
register the COM component after the build process. Fortunately, on the
development machine Visual Studio 2010 does the work for you. (This
requires the IDE to be launched with elevated privileges.) Therefore,
simply compile the project to have a class library that is consumable
from the COM architecture.