45

I found code something like the following in a 3rd party library we're using.

[CoClass(typeof(BlahClass))]
public interface Blah : IBlah
{
}

What is this doing exactly? The msdn documentation didn't illuminate the subject sufficiently for me to follow.

Robert Gowland
  • 7,677
  • 6
  • 40
  • 58
  • 1
    `CoClass` is a COM concept. If you don't understand COM, then you won't understand `CoClass`. – John Saunders Aug 05 '11 at 18:25
  • 5
    The discussion on this question might help: http://stackoverflow.com/questions/1093536/how-does-the-c-compiler-detect-com-types – rsbarro Aug 05 '11 at 18:27
  • Possible duplicate of [How does the C# compiler detect COM types?](https://stackoverflow.com/questions/1093536/how-does-the-c-sharp-compiler-detect-com-types) – adjan Oct 09 '18 at 16:08

1 Answers1

63

It declares that the interface Blah is intended to be implemented by a specific class. It means that you can conveniently say new Blah and the runtime will know what object to create - something that is not normally possible with an interface.

If you look at the generated declaration for BlahClass, it will presumably have a Guid associated with it which can be used to create an instance of a COM object.

Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
  • OK, that makes sense in light of what I'm seeing in the surrounding code. Thanks! Besides the COM thing, is there any advantage to this method vs. just implementing the interface? – Robert Gowland Aug 05 '11 at 20:42
  • I need the answer of your comment @RobertGowland. Is it nessecary to implement this class or declaring the interface would be enough? – Rikki Nov 29 '12 at 12:38
  • 2
    @MohammadGoudarzi The attribute `[CoClass(typeof(BlahClass))]` mentions the class `BlahClass`, so that class must exist somewhere. And it must implement the interface `Blah`. In an interop assembly generated from a COM type library, `BlahClass` will really be a COM object (possibly implemented in C++, VB6, Delphi or something else entirely...) – Daniel Earwicker Jan 17 '13 at 15:39