I am trying to make a C# for loop that will loop through an array of items and print the first date of the user. Below is the code for the array (which i think is correct).
string[,] arrHolidays = new string[2, 3];
arrHolidays[0, 0] = "10/05/2015";
arrHolidays[0, 1] = "15/05/2015";
arrHolidays[0, 2] = "Danny";
arrHolidays[1, 0] = "20/05/2015";
arrHolidays[1, 1] = "22/05/2015";
arrHolidays[1, 2] = "Kieran";
Below is the code for the For loop (which is throwing the error)
for(int i = 0; i < arrHolidays.Length; i++)
{
Console.WriteLine(arrHolidays[i, 0]);
}
Index out of range exception was unhandled. this is the error I am recieving. When it throws the error and I check the value of 1 it is 2 if this is any help in resolving it.
What I am expecting to see is this in the console app:
10/05/2015
20/05/2015
INB4 I have hardly any c# experience this is my first project, so please explain any help :)
You must use GetLength method, not the Length property.
The Length property for a multi-dimensional array returns the total count of all the items in the array. The GetLength method returns the number of size of a given dimension (where dimension is specified as a zero-based index).
So, arrHolidays.Length will return 6.
Change for loop to:
for (int i = 0; i < arrHolidays.GetLength(0); i++)
{
Console.WriteLine(arrHolidays[i, 0]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With