Search code examples
c#arraysinsertionindexoutofrangeexception

Inserting element into array using c#


        int[] arr = {4,3,6,7,9,12};

        int n = arr.Length;
        n = n + 1;

        for (int i =n;i>2;i--) { 
        arr[i-1] = arr[i-2];

        }

        arr[0] = 4;

The above code returning

indexOutOfRangeexception.


Solution

  • int n = arr.Length //n=6
    n=n+1 //n=7
    for(int i=n;i>2;i--){ //i=7
      arr[i-1] //arr[6]
    

    While clearly the last element is arr[5]. In C# arrays are of constant length, you can't change them, the only way to do that is to create a new array, or a better solution would be using List<>