C#: Implementing Generic Method of Generic Interface Causes Runtime Exception


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.

About these ads

About Phil Harding

SharePoint Consultant, Developer, Father, Husband and Climber.

Trackbacks/Pingbacks

  1. C#: Implementing Generic Method of Generic Interface Causes … | Source code bank - April 10, 2010

    [...] the original post: C#: Implementing Generic Method of Generic Interface Causes … If you enjoyed this article please consider sharing [...]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 597 other followers

%d bloggers like this: