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?