1

I have a grid a matrix of tile.

enum Tile
{ 
    Nothing = 0,
    Forest = 1,
    River = 2,
    OB = 3
}

class Grid
{
    public const int X = 6;
    public const int Y = 6;
    private Tile[,] Board { get; set; } 
    public Grid()
    {
        Board = new Tile[X, Y];
    }
}

I want to have a Ctor that take int[,] board.

Edge case that are not :

  • Different size. can be checked with .GetLength(0) to match const int X . Throw.
  • Value that that are unknow (Tile)12, Set to default Value int =0.

So I have

public Grid(int[,] board)
{
    if (board.GetLength(0) != Y || board.GetLength(1) != X) { 
        throw new ArgumentException();            
    }

    Board = new Tile[Y, X];
    for (int i = 0; i < Y; i++)
    for (int j = 0; j < X; j++) {
        var enumValue = (Enum.IsDefined(typeof(Tile),board[i, j]))? (Tile)board[i, j]: default(Tile) ;
        Board[i, j] = enumValue;
    }
}

Is there a straight Foward way to cast int 2d array int[,] to enum 2d array enum[,]?

I try various combinaison of Cast, as, (). Without sucess.

Drag and Drop
  • 2,672
  • 3
  • 25
  • 37

1 Answers1

4

Due to the way .NET was originally set up to deal with array covariance, it is actually possible to directly cast an array of derived[] to an array of base[]. This is generally considered to be a bad idea.

However, in the case of an enum[] you can always cast to int[] safely. This is because an enum by default is an int underneath. (If you have an enum : byte you can cast to byte[].)

But C# will not let you do it easily. You need to cast to object first.

public Grid(int[,] board)
{
    if (board.GetLength(0) != Y || board.GetLength(1) != X) { 
        throw new ArgumentException();            
    }

    Board = (Tile[,])(object)board;
}

This is somewhat unsafe as it just stores the array that was passed in. If you want a copy, just call Clone:

public Grid(int[,] board)
{
    if (board.GetLength(0) != Y || board.GetLength(1) != X) { 
        throw new ArgumentException();            
    }

    Board = (Tile[,])board.Clone();
}
Charlieface
  • 52,284
  • 6
  • 19
  • 43