I have a generic class, say MyCollection<T>, that needs its generic type T have a parameterless constructor. I have an interface IMyInterface with all implementetations having parameterless contructors, but I cannot tell that fact to the compiler, so I cannot use IMyInterface as the type parameter T. What should I do?
public class MyCollection<T> where T : new()
{
bla bla ...
T t = new T();
}
public interface IMyInterface
{
bla bla ...
}
...
MyCollection<IMyInterface> x; //Compile Time Error
I know that almost the same question was asked in Interface defining a constructor signature? but it is two years old and I’m hoping maybe someone can suggest a workaround in C# 4.0.
This won’t work because
T t = new T();with the interface as T, it would becomeIMyInterface t = new IMyInterface();which is completely invalid. You have to know what the concrete implementation to construct your type. You cannot use an abstract type or interface alone with new. If MyCollection is your own class if you added a parameter in the constructor to setT tin the constructor by passing in your concrete implementation and remove the new parameter constraint and use the interface as a generic parameter then.