Why does the following code throw an exception?
for (int i = 0; i <= Items.Length-1; i++) { Console.WriteLine(Items[i,1]); }
Exception:
System.IndexOutOfRangeException was unhandled Message='Index was outside the bounds of the array.' Source='Es' StackTrace: at Es.Program.Main(String[] args) in C:\Users\Fero\Documents\Visual Studio 2005\Projects\Es\Es\Program.cs:line 19 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()
Declaration of Items:
Function which gets the array of strings:
static string[,] ReadFromFile(string filename, int rowsF) { StreamReader SR; string S; string[] S_split; SR = File.OpenText(filename); S = SR.ReadLine(); string[,] myItems = new String[rowsF, 2]; int row_number = 0; while (S != null) { S_split = S.Split('''); //temp_items[row_number,0] = myItems[row_number,0] = S_split[1]; myItems[row_number,1] = S_split[2]; row_number++; S = SR.ReadLine(); } SR.Close(); return myItems; } string[,] Items = ReadFromFile(myFile, rowsF);
You have a straight two-dimensional array. Length gives you the total number of elements in the array, but you’re using it to calculate the index for a single dimension. What you want is: