Wednesday 26 September 2018

What is ArrayList in C#?

What is ArrayList in C#?

The ArrayList collection is similar to the Arrays data type in C#. The biggest difference is the dynamic nature of the array list collection.
For arrays, you need to define the number of elements that the array can hold at the time of array declaration. But in the case of the Array List collection, this does not need to be done beforehand. Elements can be added or removed from the Array List collection at any point in time. Let's look at the operations available for the array list collection in more detail.

Declaration of an Array List

The declaration of an ArrayList is provided below. An array list is created with the help of the ArrayList Datatype. The "new" keyword is used to create an object of an ArrayList. The object is then assigned to the variable a1. So now the variable a1 will be used to access the different elements of the array list.

ArrayList a1 = new ArrayList() 

Adding elements to an array

The add method is used to add an element to the ArrayList. The add method can be used to add any sort of data type element to the array list. So you can add an Integer, or a string, or even a Boolean value to the array list. The general syntax of the addition method is given below

ArrayList.add(element)


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoApplication
{
 class Program
 {
  static void Main(string[] args)
  {
   ArrayList a1 = new ArrayList();
   a1.Add(1);
   a1.Add("Example");
   a1.Add(true);
   
   Console.WriteLine(a1.Count);
   Console.WriteLine(a1.Contains(2));
   Console.WriteLine(a1[1]);
   a1.RemoveAt(1);
   Console.WriteLine(a1[1]);
   Console.ReadKey();
  }
 }
}

No comments:

Post a Comment

What is ArrayList in C#?

What is ArrayList in C#? The ArrayList collection is similar to the Arrays data type in C#. The biggest difference is the dynamic natur...