- Home /
Strange behaviour with List C#
Hi I have an issue with List in my code (or something is off elsewhere). I have a class Chunk which holds some terraintiles.
I add Chunks to a List array in my main class.
private List<Chunk> chunks = new List<Chunk>();
Chunk newChunk = new Chunk(0, 0);
newChunk.GRID_SIZE = GRID_SIZE;
newChunk.TILE_SIZE = TILE_SIZE;
newChunk.InitiateTerrain();
chunks.Add(newChunk);
Then I have a help method
Chunk getChunkAt(int xPos, int yPos) {
foreach(Chunk chunk in chunks) {
if(chunk.x == xPos && chunk.y == yPos) {
return chunk;
}
}
return null;
}
This method finds Chunks, I have even logged just before the "return" statement. The if statement works, it finds chunk.x and chunk.y but if I log the chunk object, it returns null, no matter how I access it.
chunks[0] // This returns null
getChunkAt(0,0) // This returns null
etc...
What am I doing wrong. I heard something about "as-cast" issues with C# but I dont understand what Im missing with casting. Im using List and although I cast it to (Chunk) it still turns up to null.
I don't spot any problems here. Given accessing with chunks[0] ALSO returns null, it's probably got nothing to do with your Get() method. You're either calling chunks[0] before the zeroth element exists, some other code is overwriting list elements, or some other code nullifies the chunk object itself.