O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.24. Retrofitting a Class to Interoperate with COM

Problem

An existing C# class needs to be usable by a COM object or will need to be usable sometime in the future. You need to make your class work seamlessly with COM.

Solution

Microsoft has made COM interop quite easy. In fact, you really have to do only two minor steps to make your code visible to COM:

  1. Set the Register for COM interop field in the project properties to True. This produces a type library that can be used by a COM client.

  2. Use the Regasm.exe command-line tool to register the class. For example, to register the type library for the ClassLibrary1.dll, you would do the following:

    regasm ClassLibrary1.dll /tlb:ClassLibrary1.tlb

By default, this tool will make many decisions for you. For example, new GUIDs are created for your classes and interfaces unless you specify a particular GUID to use. This can be a bad thing; it is usually a good idea to explicity specify which GUIDs your classes and interfaces are to use. To take control of how your C# code is viewed and used from a COM client, you need to use a few attributes. Table 3-4 contains a list of attributes and their descriptions that can be used to control these things.

Table 3-4. Attributes to control how a COM client views and is able to use your C# code

Attribute name

Description

GuidAttribute

Places a GUID on an assembly, class, struct, interface, enum, or delegate. Prevents the Tlbimp (the type library converter tool, which converts a COM type library into ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required