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 a new() constraint to your type parameter:
void Add<T>() where T : new() { ... new T() ... } You also need a constraint T : A so that you can add your object of type T to a List<A>.
Note: When you use new() together with other contraints, the new() constraint must come last.
Related
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With