How to Insert An Element Into An Array In C#

Introduction 

This article will teach us how to insert an element into an array. The array is a collection of items stored at contiguous memory locations in C#. Here you will create an array of integers that contains an integer value and insert an element at a given (specified) position. Given an array of integers and you have to insert an item (element/number) at a specified (given) position to insert an element into an array at a given position in C#. 

int[] myArray = { 1, 2, 3, 4, 5 };
int indexToInsert = 2;
int elementToInsert = 10;

Array.Resize(ref myArray, myArray.Length + 1); // increase array length by 1
Array.Copy(myArray, indexToInsert, myArray, indexToInsert + 1, myArray.Length - indexToInsert - 1); // shift elements right from the index
myArray[indexToInsert] = elementToInsert; // insert element at the index

foreach(int num in myArray) {
    Console.WriteLine(num);
}

In this example, we first create an array myarray containing five integers. We then specify the index at which we want to insert the new element (2) and the element itself (10). We use the Array.Resize() method to increase the size of the Array by 1. We then use the Array.Copy() method to shift all elements to the right of the index one position to the right. Finally, we insert the new element into the specified index using the assignment operator.

To insert an element into an array, you need to perform the following steps

1. Declare and initialize the Array

First, you must declare an array variable and initialize it with some values. For example, let's create an array of integers with five elements.

int[] myArray = { 1, 2, 3, 4, 5 };

2. Determine the index at which you want to insert the element

The next step is determining the index where you wish to insert the new element. For example, let's say we want to insert the element 10 at the index 2 of the myArray.  

int indexToInsert = 2;
int elementToInsert = 10;

3. Resize the Array

Since arrays in C# have a fixed size, you need to resize the Array to make room for the new element. You can use the Array.Resize() method to resize the Array. This method takes two parameters: a reference to the Array and the new size of the Array. In this case, we want to increase the size of the Array by one 

Array.Resize(ref myArray, myArray.Length + 1);

The ref keyword is used to pass the Array by reference, which means that changes made to the Array in the Resize method will affect the original array variable.

4. Shift the elements to the right

Once the Array has been resized, you need to shift all elements to the right of the index one position to the right. You can use the Array.Copy() method to copy the elements from the original Array to the resized Array. This method takes four parameters: the source array, the starting index in the source array, the destination array, the starting index in the destination array, and the number of elements to copy. In this case, we want to copy all elements to the right of the index to the new Array.

Array.Copy(myArray, indexToInsert, myArray, indexToInsert + 1, myArray.Length - indexToInsert - 1);

5. Insert the new element

Finally, you can insert the new element into the specified index of the Array.

myArray[indexToInsert] = elementToInsert;

6. Print the Array to verify the result

To verify that the new element has been inserted into the Array, you can print the Array.

Using the loop in C#

foreach(int num in myArray) {
    Console.WriteLine(num);
}

Putting it all together, the complete code to insert an element into an array in C# would look like this. 

 // declaring public class
    internal class Class1
    {

        // Main Method
        static public void Main()
        {

            int a = 20;
            int[] arr = new int[a];
            int b;

            // initial array of size 10
            for (b = 0; b < a; b++)
                arr[b] = b + 1;

            // print the original array
            for (b = 0; b < a; b++)
                Console.Write(arr[b] + " ");
            Console.WriteLine();

            // element to be inserted
            int x = 25;

            // position at which element
            // is to be inserted
            int pos = 10;

            // create a new array of size n+1
            int[] newarr = new int[a + 1];

            // insert the elements from the
            // old array into the new array
            // insert all elements till pos
            // then insert a at pos
            // then insert rest of the elements
            for (b= 0; b < a + 1; b++)
            {
                if (b < pos - 1)
                    newarr[b] = arr[b];
                else if (b == pos - 1)
                    newarr[b] = x;
                else
                    newarr[b] = arr[b - 1];
            }

            // print the updated array
            for (b = 0; b < a + 1; b++)
                Console.Write(newarr[b] + " ");
            Console.WriteLine();
        }
    }
}

This program inserts an element into an array at a specific position. The code initializes an array of size 20 with values from 1 to 20 and then creates a new array of size 21 to insert an element at position 10.

Here's a breakdown of the code.

The code declares an internal class called Class1.  

 The Main method is declared static and public, which means it can be accessed from outside the class and executed without creating an instance of the class. 

The code initializes an integer variable 'a' with the value 20, representing the original Array's size to be initialized.

  •  The code initializes an integer array 'arr' with a size of a.
  •  A for loop populates the 'arr' array with values from 1 to 20.
  •  Another for loop is used to print out the original Array.
  •  The code declares an integer variable 'x' with a value of 25, which is the element to be inserted.
  •  The code declares an integer variable 'pos' with a value of 10, representing the position where the element should be inserted.
  •  A new integer array, 'newarr,' is declared with a size of a + 1' to accommodate the new element.
  •  Another for loop is used to copy the elements from the old Array to the new Array.
  •  The 'if-else' conditions in the loop are used to insert the new element at the specified position in the Array.
  •  Finally, another for loop is used to print out the updated Array.

Note. that in C#, array indexes start at 0. So, if we want to insert an element at position 10, we must insert it at index 9. The code uses the condition 'if (b == pos - 1)' to insert the new element at index 9.

Output

 

You can insert an element into an array using the  Array.Copy() method or by using the Array.Resize() method. Here are examples of both methods.

  • Using Array.Copy()  
  • Using Array.Resize()  

Method 1. Using Array.Copy()  

The Array.Copy() method is used to copy elements from one Array to another array. It can copy the entire Array or a specific range of features from one Array to another.

Here is an example of how to use Array.Copy() method to copy an array.

 public static void Main()
        {
            int[] arraylist = { 1, 2, 3, 4, 5 };
            int newElement = 6;
            int[] newArray = new int[arraylist.Length + 1];

            // Copy elements from myArray to newArray
            Array.Copy(arraylist, newArray, arraylist.Length);

            // Insert new element at the end of newArray
            newArray[newArray.Length - 1] = newElement;

            // Print the contents of newArray
            Console.WriteLine("New Array:");
            for (int i = 0; i < newArray.Length; i++)
            {
                Console.Write(newArray[i] + " ");
            }
        }
    }

This statement creates an array called arraylist with five elements and a variable called newElement that represents the new element we want to insert into the Array. It then creates a new array called newArray with a length of 1 greater than the arraylist. We use the Array.Copy() method to copy the elements from arraylist into newArray, then insert the new element at the end of newArray.

Finally, we print the contents of newArray to the console using a loop. One difference between this code and the previous example is that the Main() method is declared as public static, meaning it can be called from outside of the class without needing an instance of the class. Additionally, there is no using statement at the beginning of the file to import any external libraries, so we assume that the System a namespace is already imported. 

Output 

Method 2. Using Array.Resize()  

Array.Resize() is a method that can be used to resize an array to a specified new size. This method takes two arguments the first is the Array that needs to be resized, and the second is the new size of the Array.

Here is an example of using Array.Resize().

int[] myArray = new int[5] { 1, 2, 3, 4, 5 };
        Console.WriteLine("Enter new size of array: ");
        int newSize = int.Parse(Console.ReadLine());
        Array.Resize(ref myArray, newSize);

        Console.WriteLine("New array:");
        foreach (int num in myArray)
        {
            Console.Write(num + " ");
        }
        Console.WriteLine();
    }
}

In this program, we initialize an integer array myArray, with a length of 5. We then prompt the user to enter a new size for the Array and store their input in the newSize variable. We then call Array.Resize() to resize myArray to the new size. Finally, we print out the contents of the resized Array to the console using a for-each loop. When you run this program and enter a new size of, say, 8, the output will look like this:  

Output 

Conclusion

This code example taught us How to insert an element into an array in C#. Check out Arrays in C # to learn everything about arrays in C#, check out  Arrays in C#.

FAQs 

Q- What is an array in C#?

A- An array is a data structure that stores a fixed-size sequential collection of elements of the same type. In C#, arrays can be declared and initialized in many ways, and they can be one-dimensional, multi-dimensional, or jagged. Arrays are indexed starting from 0, and the length of an array can be obtained using the Length property

Q- How to insert an element in C#?

A- you can use the Insert method of the List<T> class or the InsertAt method of the ObservableCollection<T> class in C#   

Q- Can I use the Array class to insert an element into an array?

A- No, the Array class in C# does not provide a method for inserting an element into an array. You must use the steps outlined in the previous answer to manually insert an element into an array.

Q- What happens if I try to insert an element into an array at an index that is out of range?

A- If you try to insert an element into an array at an index greater than or equal to the length of the Array, you will get an IndexOutOfRangeException at runtime. Make sure to check that the index is within the bounds of the Array before attempting to insert an element.

Q- Is it possible to insert multiple elements into an array at once?

A- Yes, you can insert multiple elements into an array at once by creating a new array larger than the original Array, copying the elements before and after the insertion point, and then inserting the new elements into the appropriate positions in the new Array.

Q- Can I insert elements into a multi-dimensional array?

A- Yes, you can insert elements into a multi-dimensional array by specifying the indices of the element you want to insert. However, inserting elements into a multi-dimensional array may be more complex than for a one-dimensional array, especially if you need to shift elements to make room for the new element.


Recommended Free Ebook
Similar Articles