hardywang
hardywang

Reputation: 5192

Define a generic class and implement generic interface

I have following code

public interface IDummy<TType> where TType : new()
{
}

public class Dummy<TType> : IDummy<TType>
{
}

And compile failed, because of Error 1 'TType' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TType' in the generic type or method 'ConsoleApplication1.IDummy<TType>' D:\Temp\ConsoleApplication1\Dummy.cs 5 18 ConsoleApplication1

But if I change code to

public interface IDummy<TType>
{
}

public class Dummy<TType> : IDummy<TType> where TType : new()
{
}

Then compile is successful. I have no way to define the generic type requirement at interface level?

Upvotes: 0

Views: 196

Answers (1)

Servy
Servy

Reputation: 203839

You need to put the restriction on both places:

public interface IDummy<TType> where TType : new()
{
}

public class Dummy<TType> : IDummy<TType> where TType : new()
{
}

Upvotes: 3

Related Questions