tags:

views:

121

answers:

3

I know this exact question has been asked, but the solution posted there doesn't seem to work for me. Here's the code I'm trying:

namespace ConsoleApplication5
{
    class Program
    {
        enum Tile { Empty, White, Black };
        using Board = Tile[8,8];

And the error I get:

Invalid token 'using' in class, struct, or interface member declaration

It seems the "using" clause must be moved outside the Program class, but my Tile enum doesn't exist there. So how am I supposed to do this?

+6  A: 

You cannot use using like that.

You can only use for concrete types, not for 'constructors' as you have used.

leppie
Whilst correct, a workaround would have given you full marks ;) Haha
Mark
+2  A: 

Unfortunately, you cannot use using to declare a name for an array type. I don’t know why, but the C# specification doesn’t allow it.

However, you can get pretty close by simply declaring Board as a new type containing the array you want, for example:

public class Board
{
    public Tile[,] Tiles = new Tile[8,8];
}

Now every time you say new Board(), you automatically get an 8x8 array of tiles.

Timwi
Well, `Board.Tiles` gives me what I want... but you're adding an extra layer that I don't want.
Mark
@Mark: So does the answer that you accepted as correct.
Timwi
How so?? both his solutions return `board` as a matrix of tiles... rather than a class *containing* the matrix I want. Not quite ideal syntax, but apparently what I wanted to do isn't possible in C#, so it's close enough.
Mark
+5  A: 

It looks like you're trying to use a name to represent a specific way of instantiating a Tile[,] array.

Why not just declare a method that does this?

Tile[,] GetBoard()
{
    return new Tile[8, 8];
}

Another option, though I'd consider this a little bit bizarre (not to mention hacky), would be to define a Board type with an implicit operator to convert to Tile[,], as follows:

public class Board
{
    private Tile[,] tiles = new Tile[8, 8];

    public static implicit operator Tile[,](Board board)
    {
        return board.tiles;
    }
}

This would actually allow you to do this:

Tile[,] board = new Board();
Dan Tao