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. Many instances of the same class by a loop

Many instances of the same class by a loop

Scheduled Pinned Locked Moved C#
database
6 Posts 6 Posters 1 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.
  • M Offline
    M Offline
    mrRsChief
    wrote on last edited by
    #1

    I have a Class called horse. Its fields are name; color; age; sex. I would like to loop thru an arry of names like trigger; royal; crown; etc. I would like to do this. foreach (string name in arrayNames) { horse name = new horse(); } Now I have a class for each horses name. Can this be done. Thanks Ray

    D W V OriginalGriffO B 5 Replies Last reply
    0
    • M mrRsChief

      I have a Class called horse. Its fields are name; color; age; sex. I would like to loop thru an arry of names like trigger; royal; crown; etc. I would like to do this. foreach (string name in arrayNames) { horse name = new horse(); } Now I have a class for each horses name. Can this be done. Thanks Ray

      D Offline
      D Offline
      Dave Kreskowiak
      wrote on last edited by
      #2

      You're creating a horse object, but then forgetting about it and it's being destroyed. You have to add each horse to a collection to keep it alive. You also should probably set the name of each horse after you create each instance of horse.

      A guide to posting questions on CodeProject

      How to debug small programs
      Dave Kreskowiak

      1 Reply Last reply
      0
      • M mrRsChief

        I have a Class called horse. Its fields are name; color; age; sex. I would like to loop thru an arry of names like trigger; royal; crown; etc. I would like to do this. foreach (string name in arrayNames) { horse name = new horse(); } Now I have a class for each horses name. Can this be done. Thanks Ray

        W Offline
        W Offline
        Wayne Gaylard
        wrote on last edited by
        #3

        You should really declare a collection of Horses, and then in your loop, create a new Horse and give a name based on the current name in the array

        List allHorses = new List();
        foreach(string name in arrayNames)
        {
        horses.Add(new Horse(){ Name = name };
        }

        Everyone dies - but not everyone lives

        1 Reply Last reply
        0
        • M mrRsChief

          I have a Class called horse. Its fields are name; color; age; sex. I would like to loop thru an arry of names like trigger; royal; crown; etc. I would like to do this. foreach (string name in arrayNames) { horse name = new horse(); } Now I have a class for each horses name. Can this be done. Thanks Ray

          V Offline
          V Offline
          V 0
          wrote on last edited by
          #4

          In addition to previous answers I would create a Dictionary [^] instead of a List (given the horsename is unique).

          Dictionary horses = new Dictionary();

          then in your loop you can do:

          foreach (string name in arrayNames)
          {
          horse h = new horse();
          //set horse properties
          horses.add(name, h);
          }

          later in code you can get the horse out of the collection using the name. In addition I would also add the name property to the horse object itself. Hope this helps.

          V.
          (MQOTD rules and previous solutions)

          OriginalGriff wrote:

          V is absolutely right

          1 Reply Last reply
          0
          • M mrRsChief

            I have a Class called horse. Its fields are name; color; age; sex. I would like to loop thru an arry of names like trigger; royal; crown; etc. I would like to do this. foreach (string name in arrayNames) { horse name = new horse(); } Now I have a class for each horses name. Can this be done. Thanks Ray

            OriginalGriffO Offline
            OriginalGriffO Offline
            OriginalGriff
            wrote on last edited by
            #5

            Just to add to the previous answers: you can't do that anyway.

            foreach (string name in arrayNames)
            {
            horse name = new horse();
            }

            Because the declaration of your new horse inside the loop "hides" the name of the string used in the foreach - which will give you a compilation error:

            A local variable named 'name' cannot be declared in this scope because it would give a different meaning to 'name', which is already used in a 'parent or current' scope to denote something else

            Instead, you probably want to call it "horse" or similar so that you can access both the horse instance you just created and the name you want to give it. BTW: You should try to follow naming conventions as they make everything slightly more understandable. And one of the conventions is that class names start with an uppercase letter: "Horse" rather than "horse":

                    string\[\] arrayNames = new string\[\] { "Trigger", "Royal", "Crown" };
                    List<Horse> horses = new List<Horse>();
                    foreach (string name in arrayNames)
                        {
                        Horse horse = new Horse();
                        horse.Name = name;
                        horses.Add(horse);
                        }
                ...
                public class Horse
                    {
                    public string Name { get; set; }
                    public int Age { get; set; }
                    public Color Colour { get; set; }
                    public string Sex { get; set; }
                    }
            

            Those who fail to learn history are doomed to repeat it. --- George Santayana (December 16, 1863 – September 26, 1952) Those who fail to clear history are doomed to explain it. --- OriginalGriff (February 24, 1959 – ∞)

            "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
            "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

            1 Reply Last reply
            0
            • M mrRsChief

              I have a Class called horse. Its fields are name; color; age; sex. I would like to loop thru an arry of names like trigger; royal; crown; etc. I would like to do this. foreach (string name in arrayNames) { horse name = new horse(); } Now I have a class for each horses name. Can this be done. Thanks Ray

              B Offline
              B Offline
              BobJanova
              wrote on last edited by
              #6

              Just to throw another thing in there, the most concise way to write this in modern C# is

              var horses = arrayNames.Select(n => new horse { name = n }).ToList();

              ToList is optional if you only ever want to enumerate over it, but it's probably what you want in this context.

              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