Generics HowTo

  • Thread starter Thread starter Jacek Jurkowski
  • Start date Start date
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

{

}
 
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>
{
}
 
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>();
 
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.
 
Back
Top