Reputation: 478
I have a class which holds a picturebox. I have created an array of objects of my class, but when I try to create a new picture box, I am getting an error stating, object reference is not set to an instance of object.
Here is how I am creating pictureboxes
GreyHound[] dog;
public Form1()
{
InitializeComponent();
dog[1].MyPictureBox = new PictureBox();
dog[1].MyPictureBox = pictureBox1;
dog[2].MyPictureBox = new PictureBox();
dog[2].MyPictureBox = pictureBox2;
dog[3].MyPictureBox = new PictureBox();
dog[3].MyPictureBox = pictureBox3;
dog[4].MyPictureBox = new PictureBox();
dog[4].MyPictureBox = pictureBox4;
Edited Code :
GreyHound[] dog;
public Form1()
{
InitializeComponent();
dog = new GreyHound[4];
dog[0].MyPictureBox = new PictureBox();
dog[0].MyPictureBox = pictureBox1;
dog[1].MyPictureBox = new PictureBox();
dog[1].MyPictureBox = pictureBox2;
dog[2].MyPictureBox = new PictureBox();
dog[2].MyPictureBox = pictureBox3;
dog[3].MyPictureBox = new PictureBox();
dog[3].MyPictureBox = pictureBox4;
}
Upvotes: 0
Views: 2222
Reputation: 174289
The code you have has several severe problems:
NullReferenceException
is two-fold:
GreyHound
, but you never initialize it. That means, that dog
is null
and trying to access dog[1]
results in a NullReferenceException.GreyHound
is a reference type that means that you will have to create an instance for each item in the array. With your current code, all items in the array are null
which leads to a NullReferenceException
when trying to access the property MyPictureBox
on any item in the array, because dog[1]
would be null
.PictureBox
to the property MyPictureBox
but you overwrite that value in the very next line with pictureBoxX
.Fix your code like so:
GreyHound[] dog = new GreyHound[4]; // solves problem 1.1
dog[0] = new GreyHound(); // solves problem 1.2
dog[0].MyPictureBox = pictureBox1;
dog[1] = new GreyHound(); // solves problem 1.2
dog[1].MyPictureBox = pictureBox2;
dog[2] = new GreyHound(); // solves problem 1.2
dog[2].MyPictureBox = pictureBox3;
dog[3] = new GreyHound(); // solves problem 1.2
dog[3].MyPictureBox = pictureBox4;
Upvotes: 3
Reputation: 17590
You do not initialize you array anywhere:
dog = new GreyHound[4];
also array indexing starts from 0 so:
dog[0].MyPictureBox = new PictureBox();
dog[0].MyPictureBox = pictureBox1;
dog[1].MyPictureBox = new PictureBox();
dog[1].MyPictureBox = pictureBox2;
dog[2].MyPictureBox = new PictureBox();
dog[2].MyPictureBox = pictureBox3;
dog[3].MyPictureBox = new PictureBox();
dog[3].MyPictureBox = pictureBox4;
Upvotes: 2