Monday, July 01, 2013

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

   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)]
public class MyClass
{
}

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.

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
{
}


Read more: Codeproject
QR: Inline image 1