Array of objects

M

Michele Santucci

Re all,

I'm a newbie in C# programming, and I'm trying to find a 'nice' solution to
this problem:
I have to initialize a 'matrix' of Cell objects where Cell is an object
class defined by myself
up to now I defined a static method that does the thing but, even if it
works, it doens't look
really nice solution.
Is it possible to overload the 'new' operator of the Cell class to do this?

Best regards,
Mike
 
K

Konrad Neitzel

Hi Michele!

I'm a newbie in C# programming, and I'm trying to find a 'nice'
solution to this problem:
I have to initialize a 'matrix' of Cell objects where Cell is an
object class defined by myself
up to now I defined a static method that does the thing but, even if
it works, it doens't look
really nice solution.
Is it possible to overload the 'new' operator of the Cell class to do
this?
The new operator cannot be overloaded in C#.

I think that the static method is already an easy solution. If you
regulary need an array of cells, it could also be nice to have your own
class for that. (e.g. you have a game board that has multiple single
cells, then I would write a class GameBoard or so and that is creating
the array of cells internaly. But without any knowledge about your
ideas, it is hard to say anything about the oo design.)

Konrad
 
F

Family Tree Mike

Re all,

I'm a newbie in C# programming, and I'm trying to find a 'nice' solution
to this problem:
I have to initialize a 'matrix' of Cell objects where Cell is an object
class defined by myself
up to now I defined a static method that does the thing but, even if it
works, it doens't look
really nice solution.
Is it possible to overload the 'new' operator of the Cell class to do this?

Best regards,
Mike

Your question is a little confusing. For example, you would not have a
constructor in your Cell class that created a matrix of Cell objects.

It sounds like you have something like the following:

public class Cell
{
public Cell() {}
}

public class CellMatrix
{
Cell [,] matrix;
public CellMatrix()
{
int nrows = 10, ncols = 10;
Cell[,] matrix = new Cell[nrows, ncols];
for (int r = 0; r < nrows; ++r)
for (int c = 0; c < ncols; ++c)
matrix[r, c] = new Cell();
}
}

Now you could have multiple constructors in the CellMatrix class,
including one that took two int parameters as the size of the matrix,
such as the following:

public CellMatrix(int nrows, int ncols)
{
Cell[,] matrix = new Cell[nrows, ncols];
for (int r = 0; r < nrows; ++r)
for (int c = 0; c < ncols; ++c)
matrix[r, c] = new Cell();
}

Is that what your question is regarding?
 

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

Top