Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Best Practice in Writing a COM-Visible Assembly (C#)

0.00/5 (No votes)
5 Mar 2014 1  
I summarized some best practice rules in writing a COM-visible assembly according to my recent work.

Introduction

I summarized some best practice rules in writing a COM-visible assembly according to my recent work.

  1. In AssemblyInfo.cs, I wrote two attributes:
    [assembly: ComVisible(false)]
    [assembly: Guid("64729ced-7a8d-4c90-af7f-a41725cfe216")] 

    They indicated I didn’t want all public classes to be COM-visible and I didn’t want Visual Studio to implicitly generate a random GUID as my library ID.

  2. I unchecked the “Register for COM interop” box in the project’s Build option because I didn’t want Visual Studio to register the assembly on the build machine.
  3. I wrote each COM-visible class like the following example:
    [ComVisible(true)]
    [Guid("7884998B-0504-4CBE-9FF9-6BBAA9776188")]
    [ClassInterface(ClassInterfaceType.None)]
    [ProgId("MyNamespace.MyClass")]
    public class MyClass : IMyClass
    {
    } 

    Here, I explicitly declared the class as COM-visible and gave it a GUID as the class ID. Visual Studio would generate a random GUID if I didn’t specify one. I used ClassInterfaceType.None to prevent Visual Studio from generating an interface for the class automatically. The automatic behavior would expose methods which I didn’t want to expose and could introduce unwanted method declarations.

    By the way, you can explicitly specify the ProgId attribute. By default, namespaces and class name will be combined as the ProgId of the class.

  4. I declared an interface for each COM-visible class explicitly like the following example:
    [ComVisible(true)]
    [Guid("67F6AA4C-A9A5-4682-98F9-15BDF2246A74")]
    [InterfaceType(ComInterfaceType.InterfaceIsDual)]
    public interface IMyClass
    {
    }

    There was no special rule for InterfaceType. It would depend on application needs. And I only declared the methods which I wanted to expose in the interface.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here