Jupiter
Jupiter

Reputation: 1502

Array and indexer in generic class

Up until now I've always been able to get an answer from an existing post on this site but today I have a question no one asked before it seems.

Its about the follow piece of code:

class Board<T>
{
    private T[,] board;

    public T[,] BoardArray
    {
        get { return (T[,])board.Clone(); }
    }

    public T this[int y, int x]
    {
        get { return board[y, x]; }
        set { board[y, x] = value; }
    }

    public Board()
    {
        board = new T[8, 8];
    }

    public void AssignToBoard()
    {
        board[1, 2] = 3;
        this[1, 2] = 3;
    }
}

The problem is that both lines of code in the method generate the same compile-time error. I know why the error is thrown but I don't know a clean work-around. This is the error:

Error   1   Cannot implicitly convert type 'int' to 'T' C:\Users\Peter\Desktop\Dropbox\ReversieAI\ReversieAI\ReversieAI\Map.cs  31  18  ReversieAI

The only way I've been able to get my code compiled is to change the lines to:

board[1, 2] = (T)(object)3;
this[1, 2] = (T)(object)3;

Although it works, it is still a dirty solution. Do any of you guys recognize the problem and can help me/share any thoughts?

Thanks in advance, Peter

Edit: I have found a solution by changing something in my architecture that removes the generic part of the class. Thank you for all your feedback. I really appreciate it.

Upvotes: 2

Views: 175

Answers (2)

Chris
Chris

Reputation: 27609

The problem seems to be that in the AssignToBoard method you are assuming that T is an int by putting integers into an array that contains Ts.

I would normally expect something like:

public void AssignToBoard(T value)
{
    board[1, 2] = value;
    this[1, 2] = value;
}

In this you are passing in a value of the correct type (T) that is being assigned.

You could then do something elsewhere like:

var myboard = new Board<int>();
myboard.AssignToBoard(3);

As an additional note your solution of using (T)(object)3 is likely to fail at runtime if T is something like string and it can't convert at runtime. You are really just pushing any problems from compile time to runtime...

Upvotes: 3

Lou Franco
Lou Franco

Reputation: 89172

AssignToBoard isn't generic, but board is.

Do you mean to move it out of Board as a test function. If so, you would be creating a Board and using it, and everything would work fine.

To test, you would use an AssignToBoard like

public void AssignToBoard()
{
    Board<int> testBoard = new Board<int>();
    testBoard[1, 2] = 3;
}

Upvotes: 1

Related Questions