I have a superclass we can call class A and few subclasses, e.g. class a1 : A, class a2 : A, … and a6 : A. In my class B, I have a set of methods that creates and adds one of the subclasses to a List<A>in B.
I want to shorten my code I have at the moment. So instead of writing
Adda1()
{
aList.Add( new a1() );
}
Adda2()
{
aList.Add( new a2() );
}
...
Adda6()
{
aList.Add( new a6() );
}
Instead I want to write something similar to this
Add<T>()
{
aList.Add( new T() ); // This gives an error saying there is no class T.
}
Is that possible?
Is it also possible to constraint that T has to be of type A or one of its subclasses?
Lee’s answer is correct.
The reason is that in order to be able to call
new T()you need to add anew()constraint to your type parameter:You also need a constraint
T : Aso that you can add your object of typeTto aList<A>.Note: When you use
new()together with other contraints, thenew()constraint must come last.Related