How to insert an item in ArrayList in C#?


To insert an item in an already created ArrayList, use the Insert() method.

Firstly, set elements −

ArrayList arr = new ArrayList();

arr.Add(45);
arr.Add(78);
arr.Add(33);

Now, let’s say you need to insert an item at 2nd position. For that, use the Insert() method −

// inserting element at 2nd position
arr.Insert(1, 90);

Let us see the complete example −

Example

 Live Demo

using System;
using System.Collections;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         ArrayList arr = new ArrayList();

         arr.Add(45);
         arr.Add(78);
         arr.Add(33);
         Console.WriteLine("Count: {0}", arr.Count);
         Console.Write("ArrayList: ");

         foreach(int i in arr) {
            Console.Write(i + " ");
         }

         // inserting element at 2nd position
         arr.Insert(1, 90);
         Console.Write("
ArrayList after inserting a new element: ");          foreach(int i in arr) {             Console.Write(i + " ");          }          Console.WriteLine("
Count: {0}", arr.Count);       }    } }

Output

Count: 3
ArrayList: 45 78 33
ArrayList after inserting a new element: 45 90 78 33
Count: 4

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 22-Jun-2020

360 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements