About Generics

T

TonyJ

Hello!

Assume I have a declared the generic class PrintableCollection<T> in this
way see below.
Here I use a restriction on the type parameter T that this type T must
implement the interface IPrintable which have method Print.
So there is a restriction set on the elements that can be stored in the
generic class PrintableCollection<T> which is that
those elements must implement the interface IPrintable.
Assume that I want to store Circles in the generic class
PrintableCollection<T>
So in this case the type Circles must implement the interface IPrintable.

Now to my question: Whithin the generic class PrintableCollection<T> I must
use some kind of collection
object that give me the possibility to actually store these Circles objects.
What is the best suitable collection object to use ?
I assume that to use a generel object like ArrayList is not a good choice do
you agree with me?
A better choice I assume is to use a generic class event here?

So how should I declare this collection object in the generic class
PrintableCollection<T>?

public class PrintableCollection<T> where T : IPrintable
{
....
....
}

//Tony
 
P

Peter Duniho

[...]
Now to my question: Whithin the generic class PrintableCollection<T> I
must
use some kind of collection
object that give me the possibility to actually store these Circles
objects.
What is the best suitable collection object to use ?

The same collection you would have used in a non-generic class. Which is
best depends on how you're going to use the collection.
I assume that to use a generel object like ArrayList is not a good
choice do you agree with me?

Yes, mainly because I don't think ArrayList is usually a good choice for
any collection. The generic collection classes are much better, IMHO.
A better choice I assume is to use a generic class event here?

Yes. Just as you'd use in a non-generic class.
So how should I declare this collection object in the generic class
PrintableCollection<T>?

Well, let's assume that the basic List<T> generic class makes sense as
your choice of collection class. Then:

List<T> list = new List<T>();

should work fine (assuming you've used "T" as the generic type parameter
for your own generic class, as you've shown in your post).

Note that none of this has to do with the constraint you made for the type
parameter. For that matter, the question as to which collection to use
doesn't really have anything to do with the generic class you made.
Though, I suppose, the example of a declaration does, marginally.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top