Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if key pair in 2D array exists?

I have this 2d array or struct

public struct MapCell
{
    public string tile;
}

public MapCell[,] worldMap;

But there's no way to check if key pair is exists in this array or not... No methods for that available.

I tried to do it like this

if (worldMap[tileX, tileY] != null) {
}

it doesnt work:

Error 1 Operator '!=' cannot be applied to operands of type 'Warudo.MapCell' and '<null>'

and for

if (worldMap[tileX, tileY].tile != null) {

it doesn't work either (exception pops up when it hits non existing element).

Index was outside the bounds of the array.

So, how do I check if key pair is exists or not?

like image 524
NewProger Avatar asked Oct 15 '25 15:10

NewProger


1 Answers

You never mentioned which error you are getting -- array out of bounds or a null reference. If you are getting array out of bounds you should precede your null check with something along the lines of...

// make sure we're not referencing cells out of bounds of the array
if (tileX < arr.GetLength(0) && tileY < arr.GetLength(1))
{
    // logic
}

Of course, it's best to just store the maximum array bounds instead of getting their lengths each time.

I also second (third?) the recommendation for using a class and not a struct.

Edit: Are you ever actually initializing this field? You haven't included it in your code sample. For example worldMap = new MapCell[100,100];, and then fill up the array...

like image 172
Chris Walsh Avatar answered Oct 17 '25 06:10

Chris Walsh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!