Collections in C#
C# includes varies classes that store the values or objects are called collections.
There are two types of collections available in C#: non-generic collections and generic collections.
The System.Collections namespace contains the non-generic collection types and System.Collections.Generic namespace includes generic collection types.
In most cases, it is recommended to use generic collections because they perform faster than non-generic collections. It also minimizes exceptions by giving compile-time errors.
Non-generic Collections in C#
- Arraylist
- Stack
- Queue
- Hashtable
Arraylist in C#
In C#, the ArrayList is a non-generic collection of objects whose size increases dynamically. It is the same as Array, except that its size increases dynamically.
An ArrayList can be used to add unknown data where you don't know the types and the size of the data.
Create an ArrayList
using System.Collections;
ArrayList arlist = new ArrayList();
// or
var arlist = new ArrayList();
// Adding Elements in ArrayList:
var arlist1 = new ArrayList();
arlist1.Add(1);
arlist1.Add("Bill");
arlist1.Add(" ");
arlist1.Add(true);
arlist1.Add(4.5);
arlist1.Add(null);
Accessing an ArrayList
The ArrayList class implements the IList interface. So, elements can be accessed using indexer, in the same way as an array. Index starts from zero and increases by one for each subsequent element.
Example
var arlist = new ArrayList()
{
1,
"Bill",
300,
4.5f
};
// Access individual item using indexer
int firstElement = (int)arlist[0]; // returns 1
string secondElement = (string)arlist[1]; // returns "Bill"
// int secondElement = (int)arlist[1]; // Error: cannot convert string to int
Insert Elements in ArrayList
Use the Insert() method to insert an element at the specified index into an ArrayList.
Example
ArrayList arlist = new ArrayList()
{
1,
"Bill",
300,
4.5f
};
arlist.Insert(1, "Second Item");
foreach (var val in arlist)
Console.WriteLine(val);
Remove Elements from ArrayList
Use the Remove(), RemoveAt(), or RemoveRange methods to remove elements from an ArrayList.
Example
ArrayList arList = new ArrayList()
{
1,
null,
"Bill",
300,
" ",
4.5f,
300
};
arList.Remove(null); // Removes first occurrence of null
arList.RemoveAt(4); // Removes element at index 4
arList.RemoveRange(0, 2); // Removes two elements starting from the 1st item (0 index)
Check Element in ArrayList: using contains keyword.
ArrayList arList = new ArrayList()
{
1,
"Bill",
300,
4.5f,
300
};
Console.WriteLine(arList.Contains(300)); // true
Console.WriteLine(arList.Contains("Bill")); // true
Console.WriteLine(arList.Contains(10)); // false
Console.WriteLine(arList.Contains("Steve")); // false
Happy Coding!!
Thanks...