24

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?

0

2 Answers 2

44

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

Sign up to request clarification or add additional context in comments.

6 Comments

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: 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.
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: 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.
Who's Lee and what's Lee's answer?
|
34
public void Add<T>() where T : A, new()
{
    aList.Add(new T());
}

1 Comment

For more information, check out msdn.microsoft.com/en-us/library/twcad0zb.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.