You have an interface declaration which includes a method signature that has a generic parameter and generic constraints.
Such an interface can be seen below;
interface MyInterface { List<T> WriteDocuments<T>(List<T> listOfEntities) where T : MyEntityBase, new(); }
And you also have a implementation class, as shown;
public class MyTextClass : MyInterface { public List<T> WriteDocuments<T>(List<T> listOfEntities) where T : MyEntityBase, new() { return null; } }
This compiles perfectly fine. At runtime however, if you attempt to instanciate the implementation class you will receive an Exception;
“Method XXX … tried to implicitly implement an interface method with weaker type parameter constraints”
According to various posts which turned up from Googling and Microsoft Connect, this is a C# compiler bug, as confirmed in this post.
In lieu of a fix to the C# compiler, there is a workaround, and that is to explicitly implement the interfaces generic methods, as shown below;
public class MyFixedTextClass : MyInterface { List<T> MyInterface.WriteDocuments<T>(List<T> listOfEntities) { return null; } }
Notice that in the explicit implementation, you must omitt the access modifiers and generic constraints.
One thought on “C#: Implementing Generic Method of Generic Interface Causes Runtime Exception”