Wrox Programmer Forums
Go Back   Wrox Programmer Forums > C# and C > C# 2005 > C# 2005
|
C# 2005 For discussion of Visual C# 2005.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the C# 2005 section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old July 4th, 2007, 09:09 AM
Authorized User
 
Join Date: Apr 2007
Posts: 28
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via AIM to Larryz
Default Generics chapter 12 difficult chapter i found ...?

Please answer some of the questions lol :

I wrote the following simple class below to clear up some points.

The class below that is from a book, and I am using it to try and make the code clear to me…

Can people please comment on what I am saying, I am sure a lot of it wont be accurate.

My comments:

The class below has a defualt and non default construct used to create instances of the class student.. Without these an object of this type cant be contructed or instaniated.

When this line is called

blank = new student();

a blank template is created for the student class. Putting a “” into the name veriable and zeror into the id…

when either property such as myStudent.Name it uses the get to return the value…

Now moving onto the Generic class Farm<T>

Where is the defualt construct ?

private List<T> animals = new List<T>();


this apppears close to it and it appear to me that the property
public List<T> Animals
        {
            get
            {
                return animals;
            }
        }
Animals is being used like a handle to set up the animals collection
Eg..

farm.Animals.Add(new Cow("Jack"));
Animals uses the get to return animals the actual collection for storing the collection of animals
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 ?

I see this simulary to mystudent.Name which is a get to access name, Via Name.


These lines are confusing

public IEnumerator<T> GetEnumerator()
        {
            return animals.GetEnumerator();
        }

I can see it’s a method, and what it returns, there is no yield and its not implemented as in the usual way…

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 ?

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..

thanks Laurence

Also I am aware ArrayList() implements GetEnumerator() as it uses a foreach command.
IEnumerator IEnumerable.GetEnumerator()
        {
            return animals.GetEnumerator();
        }


using System;
using System.Collections.Generic;
using System.Text;

namespace stud
{
    public class student
    {
        private string name;
        private int Id;
        public student()
        {
            // default contructor.
        }
        public student(string newname, int newId)
        {
            name = newname;
            Id = newId;
        }

        public string Name
        {
            get
          {
              return name;
          }
          set
            {
                name = value;
            }

        }
        public int ID
        {
            get
            {
                return Id;
            }
            set
            {
               Id = value;
            }

        }
    }
}

using System;
using System.Collections.Generic;
using System.Text;

namespace stud
{
    class Program
    {
        static void Main(string[] args)
        {
            student blank = new student();
            student myStudent = new student("Frank", 1);
            Console.WriteLine("{0} is students name {1} is students ID", myStudent.Name, myStudent.ID);
            Console.WriteLine(myStudent.ToString());
            Console.WriteLine("{0} is students name {1} is students ID", blank.Name, blank.ID);
            Console.WriteLine(blank.ToString());
            Console.ReadKey();
        }
    }
}


Generic Class is confusing



using System;
using System.Collections.Generic;
using System.Text;

namespace ch12ex02
{
  public abstract class Animal
    {
      protected string name;
      public String Name
      {
          get
          {
              return name;
          }
          set
          {
              name = value;
          }
      }
      public Animal()
      {
          // default constructor
          name = "The animal with no name ";
      }
      public Animal(string newName)
      {
          // non defualt contructor.
          name = newName;
      }
      public void Feed()
      {
          Console.WriteLine("{0} has been fed.", name);
      }
      public abstract void MakeNoise();
    }
}

using System;
using System.Collections.Generic;
using System.Text;


namespace ch12ex02
{
    public class chicken : Animal
    {
        public void LayEgg()
        {
            Console.WriteLine("{0} has laid an egg", name);
        }
        public chicken(string newName): base(newName)
        {
        }
        public override void MakeNoise()
        {
            Console.WriteLine("{0} says Cluck", name);
        }
    }


using System;
using System.Collections.Generic;
using System.Text;


namespace ch12ex02
{
   public class Cow: Animal
    {
       public void Milk()
       {
           Console.WriteLine("{0} has been milked.", name);
       }
       public Cow ( string newName ): base(newName)
       {
         //This willl call the non defualt constructor of the base animal class.
       }
       public override void MakeNoise()
       {
           Console.WriteLine("{0} says moo!", name);
       }
    }
}
}

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace ch12ex02
{
    public class Farm<T> : IEnumerable<T>
        where T : Animal
    {
        private List<T> animals = new List<T>();
        public List<T> Animals
        {
            get
            {
                return animals;
            }
        }
        public IEnumerator<T> GetEnumerator()
        {
            return animals.GetEnumerator();
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return animals.GetEnumerator();
        }
        public void MakeNoises()
        {
            foreach (T animal in animals)
            {
                animal.MakeNoise();
            }
        }
        public void FeedTheAnimals()
        {
            foreach(T animal in animals)
            {
                animal.Feed();
            }
        }
        public Farm<Cow> GetCows()
        {
            Farm<Cow> cowFarm = new Farm<Cow>() ;
            foreach (T animal in animals)
            {
                if (animal is Cow)
                {
                    cowFarm.Animals.Add(animal as Cow);
                }
            }
            return cowFarm;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;

namespace ch12ex02
{
   public class SuperCow: Cow
    {
       public void fly()
       {
           Console.WriteLine("{0} is flying", name);
       }
       public SuperCow(string newName)
           : base(newName)
       {
       }
       public override void MakeNoise()
       {
           Console.WriteLine("{0} says here i come to save the day !", name);
       }
    }

}

using System;
using System.Collections.Generic;
using System.Text;

namespace ch12ex02
{
    class Program
    {
        static void Main(string[] args)
        {
            Farm<Animal> farm = new Farm<Animal>();
            farm.Animals.Add(new Cow("Jack"));
            farm.Animals.Add(new chicken("vera"));
            farm.Animals.Add(new chicken("Sally Ally"));
            farm.Animals.Add(new SuperCow ("Kevin"));
            farm.MakeNoises();
            Farm<Cow> dairyFarm = farm.GetCows();
            dairyFarm.FeedTheAnimals();
            foreach (Cow cow in dairyFarm)
            {
                if (cow is SuperCow)
                {
                    (cow as SuperCow).fly();
                }
            }
            Console.ReadKey();
        }
    }
}



 
Old July 4th, 2007, 09:40 PM
planoie's Avatar
Friend of Wrox
 
Join Date: Aug 2003
Posts: 5,407
Thanks: 0
Thanked 16 Times in 16 Posts
Default

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





Similar Threads
Thread Thread Starter Forum Replies Last Post
Chapter 12 stingo BOOK: Beginning Access 2003 VBA 0 March 1st, 2007 05:15 PM
Name not found? chapter 1 syedmahasan BOOK: Wrox's ASP.NET 2.0 Visual Web Developer 2005 Express Edition Starter ISBN: 978-0-7645-8807-5 2 November 22nd, 2006 02:40 PM
Errors on Chapter 12 example(12.8) sonnie ASP.NET 2.0 Professional 2 June 7th, 2006 10:55 AM
Chapter 12... rrlevron BOOK: Beginning ASP 3.0 2 January 16th, 2006 01:09 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.