views:

57

answers:

4

I'm trying to create a two-dimensional array of my custom class Cell with the following code:

public class Cell
{
    int top;
    int bottom;
}

public Form1()
{
    Cell[,] elements;
    elements = new Cell[10,10];

    Random r = new Random();

    for (int i=0; i!=10; i++)
    {
        for (int j=0; j!=10; j++)
        {
            elements[i,j].top = r.Next();
        } 
    }
}

But I always receive the following error: Inconsistent accessibility: ... and something about 'Cell is less accesible'...

How do I correctly define a two-dimensional array of a custom class?

+4  A: 

I suspect you haven't actually got quite that code. I suspect you've left the "public" off the declaration of Cell in your real code, and that you've got a public method which uses it somewhere in the signature. Something like this:

class Cell { ... }

public class Foo
{
    public Cell[,] DoStuff()
    {
    }
}

Alternatively, it's possible that you've got Cell as a public class but nested within a non-nested class.

I don't think it's really got anything to do with arrays.

However, it would be a lot clearer if you'd post the full error message instead of "and something to do with"... It would also help if you'd post a short but complete program demonstrating the problem.

EDIT: As others have pointed out, the code you posted wouldn't compile, but for a different reason. I doubt that you made up an error message about inconsistent accessibility, so I strongly suspect the code you've posted isn't actually like your real code at all - at least in terms of accessibility.

Again, without seeing real code, it's very hard to give an accurate answer.

Jon Skeet
And he is trying to access the top-field, which is private.
Maximilian Mayerl
@Maximilian: Very true. Again though, I suspect we haven't seen the real code.
Jon Skeet
A: 

The accessibility error is not related to the array creating. The most common scenerio for that error is a public method with a parameter that is of a private or internal type.

Jeffrey L Whitledge
+2  A: 

The default accessibility for an attribute is private. Try this:

public class Cell
{
    public int top;
    public int bottom;
}

Better still, make them auto-properties:

public class Cell
{
    public int top { get; set; }
    public int bottom { get; set; }
}
Mitch Wheat
+1: Exactly my answer, but with code.
Martinho Fernandes
A: 

I suggest you make properties out of top and bottom fields. These have a private access hence the error:

public class Cell
{
    public int top { get; set; };
    public int bottom { get; set; };
}
bruno conde