Jump to content
  • Advertisement
Sign in to follow this  
Greycrow

C# Object Arrays

This topic is 3267 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am trying to work with an array of class objects and I'm having trouble getting it to work. When I run the code below I get an exception telling me I am trying to initialize a null value and to use the "new" keyword. I don't get it. Didn't I just do that? Thanks
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        class Dog
        {
            public
                string type;
            Dog()
            {
                type = "";
            }
        };

        public Form1()
        {
            InitializeComponent();
            getDogs();
        }

        void getDogs()
        {
            Dog[] myDogs;
            myDogs = new Dog[3];

            myDogs[0].type = "Husky";
            myDogs[1].type = "Labrador";
            myDogs[2].type = "Doberman";
        }
    }





Share this post


Link to post
Share on other sites
Advertisement
What you did was to allocate an array of 3 elements. Then you need to allocate each element.

myDogs[0] = new Dog()
myDogs[1] = new Dog()
myDogs[2] = new Dog()

Share this post


Link to post
Share on other sites
Though a better solution might be to use a collection and put the name in the constructor



public class Dog
{

public string type { get; set; }

public Dog()
{
this.type = "";
}

public Dog(string type)
{
this.type = type;
}
}

List<Dog> dogs = new List<Dog>();

dogs.Add(new Dog("Husky"));
dogs.Add(new Dog("Labrador"));
dogs.Add(new Dog("Doberman"));







Share this post


Link to post
Share on other sites
In C# 3.0, you can also use an allocator list


class Dog
{
public string Name {get; set;}
}

Dog[] dogs = new Dog[]
{
new Dog() { Name = "Rex" },
new Dog() { Name = "Rover" },
new Dog() { Name = "Bob" },
new Dog() { Name = "Dave" },
};

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!