Export (0) Print
Expand All
0 out of 1 rated this helpful - Rate this topic

Example COM Class

Visual Studio .NET 2003

This topic includes an example of a class that you would expose as a COM object. After this code has been placed in a .cs file and added to your project, set the Register for COM Interop property to True. See Build, Configuration Properties, <Projectname> Property Pages Dialog Box for more information.

Exposing Visual C# objects to COM requires declaring a class interface, an events interface (if required), and the class itself. Class members must follow these rules to be visible to COM:

  • The class must be public.
  • Properties, methods, and events must be public.
  • Properties and methods must be declared on the class interface.
  • Events must be declared in the event interface.

Other public members in the class that are not declared in these interfaces will not be visible to COM, but they will be visible to other .NET Framework objects.

To expose properties and methods to COM, you must declare them on the class interface and mark them with a DispId attribute, and implement them in the class. The order the members are declared in the interface is the order used for the COM vtable.

To expose events from your class, you must declare them on the events interface and mark them with a DispId attribute. The class should not implement this interface.

The class implements the class interface (it can implement more than one interface, but the first implementation will be the default class interface). Implement the methods and properties exposed to COM here. They must be marked public and must match the declarations in the class interface. Also, declare the events raised by the class here. They must be marked public and must match the declarations in the events interface.

For more information, see COM Interop Tutorials.

Example COM Class

using System;
using System.Runtime.InteropServices;

namespace project_name
{
   // Class interface ComClass1Interface
   [Guid("EAA4976A-45C3-4BC5-BC0B-E474F4C3C83F")]
   public interface ComClass1Interface
   {
   }

   // Events interface ComClass1Events 
   [Guid("7BD20046-DF8C-44A6-8F6B-687FAA26FA71"), 
   InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
   public interface ComClass1Events 
   {
   }

   // Class ComClass1
   [Guid("0D53A3E8-E51A-49C7-944E-E72A2064F938"),
   ClassInterface(ClassInterfaceType.None),
   ComSourceInterfaces(typeof(ComClass1Events))]
   public class ComClass1 : ComClass1Interface
   {
   }
}

See Also

Build, Configuration Properties, <Projectname> Property Pages Dialog Box

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.