NullReferenceException was unhandled c#

Hi, I keep getting an error "NullReferenceException was unhandled" when I try to initialize an array of class. follow part of the code.


   public partial class newAnimal : Form
    {
        public String diet;
        public String photofile;
        public Image picture;


        public newAnimal()
        {
          InitializeComponent();
          this.picture = Image.FromFile(photofile);
        }
       
    }
public partial class Form1 : Form
    {
        private newAnimal[] m_Animals = new newAnimal[10];
       
         public Form1()
        {
           
            InitializeComponent();
            m_Animals[0].diet = "diet name"
                           
        }
}


thanks for help
d2marceloAsked:
Who is Participating?
 
Babycorn-StarfishConnect With a Mentor Commented:
Hi,

in your Form class you need to initialise each element of the array, so change your code to:

 public partial class Form1 : Form
    {
        private newAnimal[] m_Animals = new newAnimal[10];

        public Form1()
        {
            InitializeComponent();
            for (int i = 0; i < m_Animals.Length; i++)
            {
                m_Animals[i] = new newAnimal();
            }
            m_Animals[0].diet = "diet name";
        }
    }

You'll get a new error now however because you don't have a name for the image when the newAnimal is constructed:

public String diet;
        public String photofile;
        public Image picture;

        public newAnimal()
        {
            InitializeComponent();
            //this.picture = Image.FromFile(photofile); <--------------------------------------- photofile is never set
        }

so you will need to think of a way of initialising the picture field either by changing the constructor to accept a path to a picture file, or you can create a little method like below

public String PhotoFilePath
{
      get
      {
           return photofile;
      }
      set
      {
            photofile = value; //set to the new value
            this.picture = Image.FromFile(photofile);  //update the image with the new image
       }
}

hope this helps,
           
0
 
Babycorn-StarfishCommented:
sorry, that is property, not a method :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.