How to insert an item in ArrayList in C#?

CsharpProgrammingServer Side Programming

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("\nArrayList after inserting a new element: ");

         foreach(int i in arr) {
            Console.Write(i + " ");
         }
         Console.WriteLine("\nCount: {0}", arr.Count);
      }
   }
}

Output

Count: 3
ArrayList: 45 78 33
ArrayList after inserting a new element: 45 90 78 33
Count: 4
raja
Published on 31-Aug-2018 11:35:40
Advertisements