I got "System.NullReferenceException-Additional information: Object reference not set to an instance of an object." error when I declared array of car objects and used their properties. How can I use car's properties in Form1() method?
Thanks anyone in advance!
namespace dot_moving02
{
class car
{
public int x;
public int y;
}
}
namespace dot_moving02
{
public partial class Form1 : Form
{
...
car []cars = new car;
public Form1()
{
cars = new car[10];
cars[0].x = 100; //error here
cars[0].y = 100;
}
}
Loading
Mamta MPosted Oct 30, 2008, 2:00 AM
Hi there,
What the error means is that you are trying to use an object before instantiating it. When you merely declare an object, it is not instantiated, it's just a 'reference'. You need to create an instance of the object or, in other words, instantiate the object, before attempting to use it. In your code, you had instantiated the array but not the array element.
So your Form1 constructor needs to be modified as follows:
public Form1()
{
cars = new car[10];
cars[0] = new car(); // this was missing earlier
cars[0].x = 100;
cars[0].y = 100;
}
Now, it will work successfully.
Regards,
Mamta