-2

Can someone tell me why I'm seeing below exception when I use a foreach loop?

Unhandled Exception: System.IndexOutOfRangeException:
Index was outside the bounds of the array.

but I don't see this exception if I use for loop.
One thing I have noticed is index is starting at 1 if I use foreach loop.

int[] array1 = new int[] { 1, 2, 3 };
int[] array2 = new int[] { 4, 5, 6 };

int[] mergedarray = new int[array1.Length+array2.Length];
array1.CopyTo(mergedarray, 0);
array2.CopyTo(mergedarray, array1.Length);
Console.WriteLine(mergedarray.Length);

//for (int i = 0; i < mergedarray.Length; i++)
//{
//    Console.WriteLine(mergedarray[i]); ;
//}

foreach (var item in mergedarray)
{
    Console.Write(mergedarray[item] + " ");
}
Jimi
  • 29,621
  • 8
  • 43
  • 61
Ash0214
  • 25
  • 1
  • 3
  • 1
    In a `foreach` loop there is no notion of an index. `item` represents the current item taken from your array. I.e. it starts at `1` since the first item in `array1` is `1`. If you would set the first item to be `34` then it would start with `34` instead. – Visual Vincent Jan 05 '19 at 17:38
  • 2
    Possible duplicate of [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) –  Jan 05 '19 at 17:51

2 Answers2

2

The issue is with following line

 foreach (var item in mergedarray)
 {
    Console.Write(mergedarray[item] + " ");
 }

This needs to be

 foreach (var item in mergedarray)
 {
     Console.Write(item + " ");
 }
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
0

foreach doesn't give you a index, instead it gives you the item directly out of the array, what you did only worked for you because the arrays were of the int type. You only need a index if you use for. In-depth: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/foreach-in

And your "index" started with 1 because your array started with that number.

The correct solution would be:

 foreach (var item in mergedarray)
 {
     Console.Write(item + " ");
 }

Pro tip: You can easily join array items into a string using string.Join (https://learn.microsoft.com/en-us/dotnet/api/system.string.join). It takes first a seperator string or char, in your case the space ' ' or " ", and afterwards you array.

var joinedArray = string.Join(' ', mergedarray);

With regards, 2gjava.

2gJava
  • 59
  • 6