Search code examples
c#comcomvisible

What's the deal with [ComVisible] default and public classes COM exposure?


MSDN has this article about [ComVisible] attribute. I don't quite get what happens when one sets [ComVisible(true)].

MSDN says

The default is true, which indicates that the managed type is visible to COM. This attribute is not needed to make public managed assemblies and types visible; they are visible to COM by default. Only public types can be made visible.

So they say public types are visible to COM by default. But they also say only public types can be made visible by setting [ComVisible(true)]. It does not makes sense: if public types are visible by default, then how does setting [ComVisible(true)] make public types visible? If they're already visible how will they get more visible?

Perhaps my understanding is not correct. I shall appreciate if anyone can put some light on the above statements.


Solution

  • It does not makes sense, when public types are visible by default, so how does setting ComVisible attribute to true [ComVisible(true)] makes public types visible.

    They're visible by default because the default value of the ComVisibleAttribute is true. Setting the attribute explicitly to true doesn't change anything, it just makes your intentions more clear. That's the very first line of the documentation you found:

    The default is true, which indicates that the managed type is visible to COM. This attribute is not needed to make public managed assemblies and types visible; they are visible to COM by default. Only public types can be made visible. The attribute cannot be used to make an otherwise internal or protected type visible to COM or to make members of a nonvisible type visible.

    Basically, you can think of it like the compiler always adds [ComVisibleAttribute(true)] to your code by default if you don't do it yourself.

    The only reason you would need to set this attribute is to prevent public types from being COM-visible (in which case you would set it to false). The default already ensures their visibility.

    Obviously, non-public types (e.g., private and protected) cannot and will not ever be visible to COM. This attribute has no effect on types with such accessibility.