23

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?

sehlstrom
  • 389
  • 2
  • 7
  • 18

2 Answers2

42

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

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • Thank you. This means that I can pass the class `A` as a type constraint. Is there a way that I can make it only possible to pass subclasses of `A` as a constraint? – sehlstrom Jun 27 '12 at 20:51
  • @sehlstrom: No, but you can test that at runtime if you wish and throw an exception if someone passes an object of type `A`. You might also want to consider making `A` abstract. – Mark Byers Jun 27 '12 at 20:52
  • Greate! So if `A` is abstract, I can't pass it? Or I can pass it, but i will not be possible to create an instance? – sehlstrom Jun 27 '12 at 20:54
  • @sehlstrom: If it's abstract, then it's not possible to create instances of A. This means that at runtime any argument you give must have a type that is a subclass of A. – Mark Byers Jun 27 '12 at 20:55
  • Who's Lee and what's Lee's answer? – 123iamking Dec 15 '18 at 05:13
  • Lee is Lee and Lee's answer is down there, unless it is not, in which case it is up there. – OCDev Nov 05 '21 at 05:59
34
public void Add<T>() where T : A, new()
{
    aList.Add(new T());
}
Lee
  • 142,018
  • 20
  • 234
  • 287