Reputation: 1
It's pretty simple to deal with an array with one dimension. But how can we avoid testing out of range locations within a bi dimensional array with different lengths on each row (jagged array)?
here is my code (if anyone wants to test):
static void Main(string[] args)
{
object[][] x = weirdReturn();
int k = 0;
while(x[0][k] != null) //THIS CODE PRODUCES THE EXCEPTION
{
for(int i = 0; i< x[k].Length; i++)
{
Console.Write("{0} ", x[k][i]);
}
Console.WriteLine("");
k++;
}
}
static object[][] weirdReturn()
{
DateTime d = new DateTime();
d = DateTime.Now;
object[] a2 = { 'X', 1.79, d, 100 };
object[] a1 = { 0, 'a', "objectX" };
object[][] retVal = new object[2][];
retVal[0] = a1;
retVal[1] = a2;
return retVal;
}
Upvotes: 0
Views: 158
Reputation: 10884
There is no magic to this - simply check the length and avoid indexing beyond that value minus one, as you would with a one-dimensional array.
Your code looks pretty messy, are you just trying to loop over the arrays like this?
static void Main(string[] args)
{
object[][] x = weirdReturn();
for (int i = 0; i < x.Length; i++)
{
for (int j = 0; j < x[i].Length; j++)
{
Console.Write("{0} ", x[i][j]);
}
Console.WriteLine("");
}
}
static object[][] weirdReturn()
{
DateTime d = new DateTime();
d = DateTime.Now;
object[] a2 = { 'X', 1.79, d, 100 };
object[] a1 = { 0, 'a', "objectX" };
object[][] retVal = new object[2][];
retVal[0] = a1;
retVal[1] = a2;
return retVal;
}
Upvotes: 2