Adding elements to the end of the ArrayList in C#


To add elements to the end of the ArrayList, the code is as follows −

Example

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(String[] args) {
      ArrayList list = new ArrayList();
      list.Add("Andy");
      list.Add("Gary");
      list.Add("Katie");
      list.Add("Amy");
      Console.WriteLine("Elements in ArrayList...");
      foreach (string res in list) {
         Console.WriteLine(res);
      }
      string[] strArr = { "John", "Jacob" };
      list.AddRange(strArr);
      Console.WriteLine("Elements in ArrayList...UPDATED");
      foreach(String str in list) {
         Console.WriteLine(str);
      }
   }
}

Output

This will produce the following output −

Elements in ArrayList...
Andy
Gary
Katie
Amy
Elements in ArrayList...UPDATED
Andy
Gary
Katie
Amy
John
Jacob

Example

Let us see another example −

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main(String[] args) {
      ArrayList list = new ArrayList();
      list.Add("Andy");
      list.Add("Gary");
      list.Add("Katie");
      list.Add("Amy");
      Console.WriteLine("Elements in ArrayList...");
      foreach (string res in list) {
         Console.WriteLine(res);
      }
      string[] strArr = { "John", "Jacob" };
      list.AddRange(strArr);
      Console.WriteLine("Elements in ArrayList...UPDATED");
      foreach(String str in list) {
         Console.WriteLine(str);
      }
      string[] strArr2 = { "Tim", "Tom", "David" };
      list.AddRange(strArr2);
      Console.WriteLine("Elements in ArrayList...UPDATED");
      foreach(String str in list) {
         Console.WriteLine(str);
      }
   }
}

Output

This will produce the following output −

Elements in ArrayList...
Andy
Gary
Katie
Amy
Elements in ArrayList...UPDATED
Andy
Gary
Katie
Amy
John
Jacob
Elements in ArrayList...UPDATED
Andy
Gary
Katie
Amy
John
Jacob
Tim
Tom
David

Updated on: 06-Dec-2019

139 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements