arrays of a class

  • Thread starter Thread starter Quibbles
  • Start date Start date
Q

Quibbles

Sorry if this is really basic, but I'm a c++ guy new to c#.
I'm trying to create a multidimensional array of a class, like so...

MyClass[,] theArray = new MyClass[4,4];

and calling a function in it like so...
theArray[0,0].aFunction();

yet I get a NullReferenceException whenever I run the program (no
compiler errors).
I'm pretty sure the problem is in the array because I made a nonarray
instance of the class and used it in the exact same way and
everything worked out fine.
 
Yes, you must explicitely new each object in the array. So...

MyClass[,] theArray = new MyClass[4,4];
theArray[0,0] = new MyClass();
theArray[0,1] = new MyClass();

etc...

Or use a nested for loop.

for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
theArray[i,j] = new Class();
}
}

Thanks,
Steven
Sorry if this is really basic, but I'm a c++ guy new to c#.
I'm trying to create a multidimensional array of a class, like so...

MyClass[,] theArray = new MyClass[4,4];

and calling a function in it like so...
theArray[0,0].aFunction();

yet I get a NullReferenceException whenever I run the program (no
compiler errors).
I'm pretty sure the problem is in the array because I made a nonarray
instance of the class and used it in the exact same way and
everything worked out fine.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top