C#: Trying to check what type an object is, is there any method like TryParse that takes in an object type?

C#: Trying to check what type an object is, is there any method like TryParse that takes in an object type?
typescript
Ethan Jackson

I am working on a chess game in unity. I have a multidimensional array of objects called a board that gives me the the array with either a Piece Object(custom) or an integer i.e. 0. I want to check if a given object in board is a Piece or an Integer... how can I do that? is there a try parse that takes in an object?

object[,] board = memoryBoard.createChessBoard(Piece.starting_pos); //returns a multidimensional array of type object[8,8] which either has a piece or an integer 0 int zero = 0; Debug.Log(int.TryParse(board[0, 0], out zero)); // obv this is wrong since TryParse requires a string and not an object //what I want it to return is either true or false depending upon whether my object is of type int or not

Answer

Don't use 0 for this in the first place. Nor object. Create your array of Piece objects, and anywhere that there's no "piece" just leave it null.

Piece[,] board = SomeMethodToBuildTheBoard(); Debug.Log(board[0, 0] is null);

In this case you're using 0 as a "magic value" to indicate that "there is nothing here". But null already means exactly that. And I'd argue that any time one finds oneself using object then it's worth examining if one isn't using types effectively. It's handy sometimes, but when used as a general bucket for any value that might be there then that often causes far more problems than it solves.

Related Articles