Creating instances of objects in an array?
I have a Cars class already created and using a form, I am trying to create an array of classes and set each member of the array with an instance of the class. I am trying to do this within the public partial class form1 : form that Visual studio creates. I am getting an error when I try to create an instance of the class after I create the array. here is the code and the errors I am getting.
Code:
namespace VirtualRace
{
public partial class Form1 : Form
{
const int RACERS = 10;
Cars[] driver = new Cars[RACERS];
driver[0] = new Cars("Andretti", 30, 0);
driver[1] = new Cars("Patrick", 30, 0);
driver[2] = new Cars("Elvers", 30, 0);
driver[3] = new Cars("Smith", 30, 0);
driver[4] = new Cars("Archibald", 30, 0);
driver[5] = new Cars("Law", 30, 0);
driver[6] = new Cars("Johnson", 30, 0);
driver[7] = new Cars("Petty", 30, 0);
driver[8] = new Cars("Freeman", 30, 0);
driver[9] = new Cars("Busch", 30, 0);
private int raceLength = 1000;
private bool winner = false;
private int leadLocation = 0;
private int leadDriver = 0;
public Form1()
{
InitializeComponent();
}
}
}
And the errors I am getting are: (there are these 4 errors per line starting on the driver[0] line and going till driver[9])
(16,16): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
(16,19): error CS1519: Invalid token '=' in class, struct, or interface member declaration
(16,25): error CS1520: Method must have a return type
(16,30): error CS1031: Type expected
Basically I am wondering how I can fill this array with these objects and keep them global to this class so I can use them in any Method I create? The code seems to work if I create the array and create each member within a single method, but not when I try it like this to make it available to the whole class. Any help is appreciated.