Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# create Object obj = new T()? [duplicate]

Tags:

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?

like image 273
sehlstrom Avatar asked Jun 27 '12 20:06

sehlstrom


1 Answers

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

  • Constraints on Type Parameters
like image 97
Mark Byers Avatar answered Oct 20 '22 10:10

Mark Byers