#1,030 – Requiring Generic Type Parameters to Derive from a Specified Class
February 11, 2014 3 Comments
By default, when you specify a type parameter in a generic class, the type can be any .NET type. There are times, however, when you’d like to constrain the type in some ways, allowing only certain types.
You can constrain a type parameter to be of a type that derives from (or is identical to) a particular type, using the where keyword. In the example below, the PileOf class has a type parameter that must derive from Animal–because we look for a Habitat property.
public class PileOf<T> where T : Animal { private List<T> thePile; private List<string> habitats; public PileOf() { thePile = new List<T>(); habitats = new List<string>(); } public void AddThing(T thing) { thePile.Add(thing); habitats.Add(thing.Habitat); } }
We can construct a PileOf<Dog>, but not a PileOf<int>.
// Works PileOf<Dog> dogPile = new PileOf<Dog>(); dogPile.AddThing(new Dog("Fido")); // Compile-time error: int can't be converted to Animal PileOf<int> intPile = new PileOf<int>();
what’s the difference between?
public class PileOf where T : Animal
public class PileOf
you can still pileof
If you use: class PileOf where T : Animal
The type T used to construct the type must derive from animal.
If you use: class PileOf without the where clause,
you can use any type for T
Pingback: #1,035 – Summary of Type Parameter Constraints | 2,000 Things You Should Know About C#