Generics HowTo

J

Jacek Jurkowski

How to ensure that generic Collection
accept only String as a typeparam?
This causes an compiler error...

public class StringCollection<T> : List<T> where T : String

{

}
 
J

Jon Skeet [C# MVP]

Jacek Jurkowski said:
How to ensure that generic Collection
accept only String as a typeparam?
This causes an compiler error...

public class StringCollection<T> : List<T> where T : String
{

}

If you only want to be able to accept a single type as the type
parameter, it's not really generic any more. Just use:

public class StringCollection : List<string>
{
}
 
J

Jacek Jurkowski

Dou You think I better derive from CollectionBase instead
of using generics? Why a cant use "where T : String"?
If you only want to be able to accept a single type as the type
parameter, it's not really generic any more. Just use:

public class StringCollection : List<string>
{
}

Its still possible: StringCollection<int> = new StringCollection<int>();
 
D

Daniel O'Connell [C# MVP]

Jacek Jurkowski said:
Dou You think I better derive from CollectionBase instead
of using generics? Why a cant use "where T : String"?


Its still possible: StringCollection<int> = new StringCollection<int>();

It shouldn't be, since StringCollection has no generic type. You don't want

public class StringCollection<T> : List<string> { };

you want
public class StringCollection : List<string> { };

You might want to look into the Collection<T> class as well if you need more
flexibility than List<T> offers.
 

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