Why can't I enforce derived classes to have parameterless constructors?
Posted
by FrisbeeBen
on Stack Overflow
See other posts from Stack Overflow
or by FrisbeeBen
Published on 2010-04-16T08:55:57Z
Indexed on
2010/04/16
9:33 UTC
Read the original article
Hit count: 165
I am trying to do the following:
public class foo<T> where T : bar, new()
{
public foo()
{
_t = new T();
}
private T _t;
}
public abstract class bar
{
public abstract void someMethod();
// Some implementation
}
public class baz : bar
{
public overide someMethod(){//Implementation}
}
And I am attempting to use it as follows:
foo<baz> fooObject = new foo<baz>();
And I get an error explaining that 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method. I fully understand why this must be, and also understand that I could pass a pre-initialized object of type 'T' in as a constructor argument to avoid having to 'new' it, but is there any way around this? any way to enforce classes that derive from 'bar' to supply parameterless constructors?
© Stack Overflow or respective owner