It seems your questions here have more to do with interface implementation, implementation delegation and encapsulation and not so much about generics.
Quote:
quote:If we substitute animals for Animals we are adding via animals.Add to this collection ?
Initialy to me, it seems the get should be be a set as this seems to be setting values ?
|
The 'animals' variable is an internal variable in the Farm class. It is a list of animals. The class uses a property to expose this internal instance. If you were to change the property to a Set only, you would only be able to change the instance of the variable, not access its members (i.e. the Add() method on it). Thus, the only requirement for it is a Get in order to get a reference to the internal instance. (This is encapsulation.)
Quote:
quote:Also the line return animals.GetEnumerator(); The book says you simply return the enumerator returned by Animals�. ?
But Farm<T> : IEnumerable<T> inherits from this inteface not Animals ?
|
Yes, you are correct. Farm implements IEnumerable<T>. It *contains* a List<T> called animals. The GetEnumerator() method of the Farm class (which is a required implementation dictated by IEnumerable<T>) is delegating the responsibility of getting an enumerator to the 'animals' internal instance of List<T>. The reason for this is that the Farm class is not inherently a "list" type class (because it doesn't inherit from a list type). But we want it to behave as such so we implement the IEnumerable<T> interface and pass off the responsibility of creating the enumerator to 'animals'. This is implementation delegation.
Quote:
quote:animals is just a type, that contains the collection of animals, I can see you are trying to iterate through it in the foreach loop, but where is it implemented..
should it be (obviously not it wont work) but Farm<T>.Animals.GetEnumerator()
what is this a method a it looks odd the way its defined plus where is it implemented..
|
'animals' is not a type. List<T> is a type. 'animals' is an instance of the type List<T>. 'animals' does not contain but rather it *is* the collection of animals. List<T> already implements the necessary methods (by means of the IEnumerable<T> interface that allow you to use it in a foreach.
Farm<T>.Animals.GetEnumerator() won't work because Farm<T> is a type not an instance.
However this would work:
Farm<Cow> objFarm = new Farm<Cow>();
objFarm.Animals.Add(new Cow());
objFarm.Animals.GetEnumerator(); //this is provided by the implementation of List<T>.GetEnumerator() thru delegation to the internal 'animals'.
I hope this helps to clear things up.
-
Peter