I am trying to make a multidimensional List that can be accessed and set in the following way:
myObjectVar[1,2,3] = new MyObject();
I have overloaded [,,] in the following way, but the Inserts never get run. What is the correct way to check to see if an index exists because the below code doesn’t seem to be working.
public myObject this[int x, int y, int z] {
get {
return _myObject[x][y][z];
}
set {
if(_myObject.Count < x){
_myObject.Insert(x, new List<List<myObject>>());
}
if(_myObject[x].Count < y){
_myObject[x].Insert(y, new List<myObject>());
}
if(_myObject[x][y].Count < z){
_myObject[x][y][z].Insert(z, value);
}
else{
_myObject[x][y][z] = value;
}
}
}
I am assuming you want to create something like a multidimensional array where you don’t have to specify bounds and that is expanded as you set the elements.
In that case, what is wrong with your code is that you use
Insert(). That method can be used to insert items in the middle of an existing list, but not beyond. So, if you have empty list, you can’t insert something at the position2.If you want to do this, you have to expand the lists manually by calling
Add()in a loop.But if you are expecting very sparse structure (that is, most elements are not set), you should probably use something like
Dictionary<int, Dictionary<int, Dictionary<int, T>>>.