Class Constructor not getting called when creating array of class object
-
I am trying to create an array of classes however when I try to assign values to the class variables I get an error: "Object reference not set to an instance of an object" Am I declaring my array wrong?
public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Button btn_FillArray ... //other controls MyClass[] classArray = new MyClass[5]; } private void btn_FillArray_Click(object sender, System.Eventargs e) { classArray[0].data = 5; } class MyClass { public MyClass() { data = 1; } public int data; }
Thank you for the help - mutty -
I am trying to create an array of classes however when I try to assign values to the class variables I get an error: "Object reference not set to an instance of an object" Am I declaring my array wrong?
public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Button btn_FillArray ... //other controls MyClass[] classArray = new MyClass[5]; } private void btn_FillArray_Click(object sender, System.Eventargs e) { classArray[0].data = 5; } class MyClass { public MyClass() { data = 1; } public int data; }
Thank you for the help - muttyHi Each element of the array has to be "newed" up individually, after the array has been declared. The array delcaration just frees up space for the number of objects, it doesn't instantiate them.
MyClass[] classArray = new MyClass[5];
for (Int32 i = 0; i < classArray.Length; i++)
classArray[i] = new MyClass();Hope that helped. Sean
-
Hi Each element of the array has to be "newed" up individually, after the array has been declared. The array delcaration just frees up space for the number of objects, it doesn't instantiate them.
MyClass[] classArray = new MyClass[5];
for (Int32 i = 0; i < classArray.Length; i++)
classArray[i] = new MyClass();Hope that helped. Sean