Tony wrote:
Hello!
I have some classes below.
I have also a generic collection class with this class header definition.
public class Farm<T: IEnumerable<Twhere T : Animal {...}
Now to my question according to a book that I read it says:
"The type of this list is determined by the type parameter T that is passed
to Farm<Tand
is constraned to be or inherit from Animal."
Because class Animal is abstract it's not possible to create an instance of
that class.
So what does this where T : Animal mean
I assume it means that T can be of a type derived from Animal or Animal
itself but
in some cases as in my case Animal itself are not allowed because it's an
abstract class.
Does my conclusion sound reasonable?
public abstract class Animal {. . .}
public class Chicken : Animal {...}
public class Cow : Animal {...}
public class SuperCow : Cow {...}
//Tony
No that is not correct. The fact that the Animal class is abstract
doesn't disqualify it from being used as T in the Farm class. You can
still create a Farm of the Animal type:
Farm<Animalfarm = new Farm<Animal>();
In this farm you can have any object that is an Animal. You can't create
instances of the Animal class, of course, but anything that you put in
the Farm<Animalwill be treated as an instance of Animal.
If you create some Cow instances and some Chicken instances and put in
the Farm<Animal>, and then loop through the contents of the farm, you
will get Animal references:
foreach (Animal animal in farm) { ... }
In the Farm<Tclass you can do anything to the animals that is defined
in the Animal class. The fact that the Animal class is abstract is not a
problem, as the Farm<Tclass is not allowed to create instances of T
anyway.
If you specify that T has to have a usable parameterless constructor,
then the Farm<Tis allowed to create instances of T, and you can only
use non-abstract classes as T:
public class Farm<T: IEnumerable<Twhere T : Animal, new() {...}
--
Göran Andersson
_____
http://www.guffa.com