Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to implement a COM interface with a .NET generics class?

I have the following interface which I'm trying to make COM-visible. When I try to generate the type-library it doesn't like the fact that my implementation class derives from a generic-class.

Is it possible to use a generic class as a COM implementation class? (I know I could write a non-generic wrapper and export that to COM, but this adds another layer that I'd rather do without.)

[ComVisible(true)]
public interface IMyClass
{
   ...
}

[ComVisible(true), ComDefaultInterface(typeof(IMyClass))]
[ClassInterface(ClassInterfaceType.None)]
public class MyClass : BaseClass<IMyClass>, IMyClass
{
   ...
} 

Error message:

Warning: Type library exporter encountered a type that derives 
from a generic class and is not marked as 
[ClassInterface(ClassInterfaceType.None)]. Class interfaces cannot
be exposed for such types. Consider marking the type with 
[ClassInterface(ClassInterfaceType.None)] 
and exposing an explicit interface as the default interface to 
COM using the ComDefaultInterface attribute.
like image 397
user3891 Avatar asked Sep 25 '08 17:09

user3891


People also ask

Can a generic class implement an interface?

Only generic classes can implement generic interfaces. Normal classes can't implement generic interfaces.

How can use generics with interface in C#?

You can declare variant generic interfaces by using the in and out keywords for generic type parameters. ref , in , and out parameters in C# cannot be variant. Value types also do not support variance. You can declare a generic type parameter covariant by using the out keyword.

CAN interface have generics?

Generic interfaces can inherit from non-generic interfaces if the generic interface is covariant, which means it only uses its type parameter as a return value.


1 Answers

Generic types and types that derive from a generic type cannot be exported. Set ComVisible(false) on your MyClass type. You'll need to either create a non-generic class implementation or use the interface only.

like image 56
Joseph Daigle Avatar answered Sep 23 '22 00:09

Joseph Daigle