Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. 'List' help ?

'List' help ?

Scheduled Pinned Locked Moved C#
csharphelpquestionlearning
9 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N Offline
    N Offline
    nlowdon
    wrote on last edited by
    #1

    Evening all (depending where you are of course !) This is going to be tricky to explain but i'll give it my best. Please bear in mind i am a novice to C#. I'm going to run a loop to create a 'List' of 10 animals. I'm using polymorhism to then cast each animal the type i need (cat, dog, etc).

    newAnimals[0] = new Cat();

    newAnimals[1] = new Cat();

    I'm confused as to how i can then give each object a reference name so that i can reference individual object's and invoke methods on them ? For instance - say i had 5 animas in the list and the first 2 were cats. I need to be able to say -

    cat1.eat();

    cat2.play();

    Is there a way i can do this ? Thanks in advance (loving the forum by the way !!)

    P C 2 Replies Last reply
    0
    • N nlowdon

      Evening all (depending where you are of course !) This is going to be tricky to explain but i'll give it my best. Please bear in mind i am a novice to C#. I'm going to run a loop to create a 'List' of 10 animals. I'm using polymorhism to then cast each animal the type i need (cat, dog, etc).

      newAnimals[0] = new Cat();

      newAnimals[1] = new Cat();

      I'm confused as to how i can then give each object a reference name so that i can reference individual object's and invoke methods on them ? For instance - say i had 5 animas in the list and the first 2 were cats. I need to be able to say -

      cat1.eat();

      cat2.play();

      Is there a way i can do this ? Thanks in advance (loving the forum by the way !!)

      P Offline
      P Offline
      Pedram Behroozi
      wrote on last edited by
      #2

      No you can't (I don't think so), except you declare 5 variables like:

      cat1 = newAnimals[0];
      cat2 = newAnimals[1];
      ...

      Then you can use these variables. However newAnimal[0].eat should work for you...

      Life is 5: 3 me, 1 you. Trying to find the missing part is the meaning of Life. And sadness is when you find that part!

      1 Reply Last reply
      0
      • N nlowdon

        Evening all (depending where you are of course !) This is going to be tricky to explain but i'll give it my best. Please bear in mind i am a novice to C#. I'm going to run a loop to create a 'List' of 10 animals. I'm using polymorhism to then cast each animal the type i need (cat, dog, etc).

        newAnimals[0] = new Cat();

        newAnimals[1] = new Cat();

        I'm confused as to how i can then give each object a reference name so that i can reference individual object's and invoke methods on them ? For instance - say i had 5 animas in the list and the first 2 were cats. I need to be able to say -

        cat1.eat();

        cat2.play();

        Is there a way i can do this ? Thanks in advance (loving the forum by the way !!)

        C Offline
        C Offline
        Christian Graus
        wrote on last edited by
        #3

        If you need to tell which animals are of what type to do something specific with them, then your inheritance tree is probably broken. You can add methods like GetAllCats, tho. Then you can do this: foreach(Animal animal in newAnimals) { Cat c = animal as Cat; if (c != null) { // Add c to a list to return, or do something with c } } The as keyword attempts to cast an object as a derived object, and returns null if it fails. I would also use a list instead of an array, so you can add as many animals as you like, unless your class requires you to use arrays at this point. If you just mean accessing the objects, then newAnimals[0], newAnimals[1] is how you reference them.

        Christian Graus Driven to the arms of OSX by Vista.

        N 1 Reply Last reply
        0
        • C Christian Graus

          If you need to tell which animals are of what type to do something specific with them, then your inheritance tree is probably broken. You can add methods like GetAllCats, tho. Then you can do this: foreach(Animal animal in newAnimals) { Cat c = animal as Cat; if (c != null) { // Add c to a list to return, or do something with c } } The as keyword attempts to cast an object as a derived object, and returns null if it fails. I would also use a list instead of an array, so you can add as many animals as you like, unless your class requires you to use arrays at this point. If you just mean accessing the objects, then newAnimals[0], newAnimals[1] is how you reference them.

          Christian Graus Driven to the arms of OSX by Vista.

          N Offline
          N Offline
          nlowdon
          wrote on last edited by
          #4

          Thanks Cristian, Your reply was v-helpful. I've since tried

          newcat1 = zooAnimals[0] as Cat;

          but this doesn't seem to work either. Can i not cast the object in this way ?

          C 1 Reply Last reply
          0
          • N nlowdon

            Thanks Cristian, Your reply was v-helpful. I've since tried

            newcat1 = zooAnimals[0] as Cat;

            but this doesn't seem to work either. Can i not cast the object in this way ?

            C Offline
            C Offline
            Christian Graus
            wrote on last edited by
            #5

            What does 'does not work' mean ? If zooAnimals is an array of Animals, and Cat is a class derived from Animal, then so long as newcat1 is a Cat and zooAnumals[0] is a Cat, it should work fine.

            Christian Graus Driven to the arms of OSX by Vista.

            N 1 Reply Last reply
            0
            • C Christian Graus

              What does 'does not work' mean ? If zooAnimals is an array of Animals, and Cat is a class derived from Animal, then so long as newcat1 is a Cat and zooAnumals[0] is a Cat, it should work fine.

              Christian Graus Driven to the arms of OSX by Vista.

              N Offline
              N Offline
              nlowdon
              wrote on last edited by
              #6

              Cristian, my appologies for not being very specific - still getting used to this 'posting' bit ! Ok - my code goes -

                      Animal newcat1;
              
                      zooAnimals = new List<Animal>();
              
                      for (i = 0; i < 2; i++)
                      {
                          Animal animal = new Animal();
                          zooAnimals.Add(animal);
                      }
              
                      newcat1 = zooAnimals\[0\] as Cat;
                      newcat2 = zooAnimals\[1\] as Cat;
              

              the program then throws a 'Null Reference - Object reference not set to an instance of an object.' When i hover the pointer, the 'newcat1' is still set to null

              L C C 3 Replies Last reply
              0
              • N nlowdon

                Cristian, my appologies for not being very specific - still getting used to this 'posting' bit ! Ok - my code goes -

                        Animal newcat1;
                
                        zooAnimals = new List<Animal>();
                
                        for (i = 0; i < 2; i++)
                        {
                            Animal animal = new Animal();
                            zooAnimals.Add(animal);
                        }
                
                        newcat1 = zooAnimals\[0\] as Cat;
                        newcat2 = zooAnimals\[1\] as Cat;
                

                the program then throws a 'Null Reference - Object reference not set to an instance of an object.' When i hover the pointer, the 'newcat1' is still set to null

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #7

                Well, you're adding Animals to the list, not Cats. So what you need to do is:

                        **Cat** newcat1;
                
                        zooAnimals = new List();
                
                        for (i = 0; i < 2; i++)
                        {
                            Animal animal = new **Cat**();
                            zooAnimals.Add(animal);
                        }
                
                        newcat1 = zooAnimals\[0\] as Cat;
                        newcat2 = zooAnimals\[1\] as Cat;
                

                regards

                1 Reply Last reply
                0
                • N nlowdon

                  Cristian, my appologies for not being very specific - still getting used to this 'posting' bit ! Ok - my code goes -

                          Animal newcat1;
                  
                          zooAnimals = new List<Animal>();
                  
                          for (i = 0; i < 2; i++)
                          {
                              Animal animal = new Animal();
                              zooAnimals.Add(animal);
                          }
                  
                          newcat1 = zooAnimals\[0\] as Cat;
                          newcat2 = zooAnimals\[1\] as Cat;
                  

                  the program then throws a 'Null Reference - Object reference not set to an instance of an object.' When i hover the pointer, the 'newcat1' is still set to null

                  C Offline
                  C Offline
                  cor2879
                  wrote on last edited by
                  #8

                  Hi there, I was looking over your post and I think this is a sample of how to accomplish what you are looking for. Look this over:

                  using System;
                  using System.Collections.Generic;

                  public abstract class ZooAnimal
                  {
                  public abstract string Speak();
                  }

                  public class Cat : ZooAnimal
                  {
                  public override string Speak()
                  {
                  return "Meow";
                  }
                  }

                  public class Lion : Cat
                  {
                  public override string Speak()
                  {
                  return "Rowr!";
                  }
                  }

                  public class Program
                  {
                  public static void Main(params string[] args)
                  {
                  List<ZooAnimal> zooAnimals = new List<ZooAnimal>();

                      for (int i = 0; i < 2; i++)
                          zooAnimals.Add(new Cat());
                  
                      for (int i = 0; i < 3; i++)
                          zooAnimals.Add(new Lion());
                  
                      for (int i = 0; i < zooAnimals.Count; i++)
                      {
                          Lion lion = zooAnimals\[i\] as Lion;
                  
                          if (lion != null)
                              Console.WriteLine("The lion says: " + lion.Speak());
                          else
                          {
                              Cat cat = zooAnimals\[i\] as Cat;
                              Console.WriteLine("The cat says: " + cat.Speak());
                          }
                      }
                  
                      Console.Read();
                  }
                  

                  }

                  See this is all just a matter of inheritance and making sure you instantiate your types correctly. In your code example you are adding two animals to the collection but trying to get out two cats. Remember - all cats are animals but not all animals are cats. To get the code you posted to work correctly, you would need to add cats to the zooAnimals collection instead of just animals. This works just fine in C# by the way - an object declared as a base type can always hold an instance of one of its derived types. To illustrate I created a three tiered inheritance example. Notice that in the above example you have ZooAnimals, Cats, and Lions. ZooAnimals is an abstract type, it exists only to serve as a base class for anything that I might consider a zoo animal. Then you have the Cat class. This is also a pretty general class - there are many types of cats, so I derived another class from Cat called Lion. Notice the hierarchy - All Lions are Cats but not all Cats are Lions (illustrated in the final for loop in the static method Main). All Cats are ZooAnimals (as far as this program is concerned at least) all ZooAnimals are not necessarily Cats. It must also follow then that since all Lions are Cats, and all Cats are ZooAnimals, then all Lions are ZooAnimals as well. Hope that

                  1 Reply Last reply
                  0
                  • N nlowdon

                    Cristian, my appologies for not being very specific - still getting used to this 'posting' bit ! Ok - my code goes -

                            Animal newcat1;
                    
                            zooAnimals = new List<Animal>();
                    
                            for (i = 0; i < 2; i++)
                            {
                                Animal animal = new Animal();
                                zooAnimals.Add(animal);
                            }
                    
                            newcat1 = zooAnimals\[0\] as Cat;
                            newcat2 = zooAnimals\[1\] as Cat;
                    

                    the program then throws a 'Null Reference - Object reference not set to an instance of an object.' When i hover the pointer, the 'newcat1' is still set to null

                    C Offline
                    C Offline
                    Christian Graus
                    wrote on last edited by
                    #9

                    I think perhaps you should do some reading on OO. As others have said, you are trying to turn an animal into a cat. It's not a cat, you didn't ask it to be.

                    Christian Graus Driven to the arms of OSX by Vista.

                    1 Reply Last reply
                    0
                    Reply
                    • Reply as topic
                    Log in to reply
                    • Oldest to Newest
                    • Newest to Oldest
                    • Most Votes


                    • Login

                    • Don't have an account? Register

                    • Login or register to search.
                    • First post
                      Last post
                    0
                    • Categories
                    • Recent
                    • Tags
                    • Popular
                    • World
                    • Users
                    • Groups