What is collection in C#

Collection classes are used to store data of specific types. All types of collection support IEnumerable interface.

Below are collection classes used in C#.net, all classes come under System.Collection namespace.

List – An array does not allow dynamic resize, but a list allows dynamic size.

Example:
List<int> list = new List<int>();
list.Add(1);
list.Add(5);
list.Add(7);
list.Add(10);

Now this list has 4 items. if you want to get item count then use list.count which returns and int which is a number of the item available in the current list.

ArrayList – ArrayList stores data of object type.

You may find the difference between List and ArrayList by looking at below example.

Creating a list of int type.

   List<int> list = new List<int>();
            list.Add(1);
            list.Add(1);
            list.Add(1);
            list.Add(“hello”); //This line will throw error as the given list is of type int and we are adding a string value.

But in ArrayList no data type is defined.

            ArrayList arList = new ArrayList();
            arList.Add(2);
            arList.Add(“string”); //In ArrayList this line will not throw any error, as no data type defined, arraylist accept data of object type.
In ArrayList casting needed.

HashTable – Hashtable uses hash code to find an element which has been added.

Stack – Stack works on LIFO i.e. Last in First Out. There are 2 operations, Push and Pop.
Queue – Queue works on FIFO i.e. First in First Out.

Dictionary – is a collection of key and value pairs. Each item in hash table is

organized using key and value pair.
Example :
        Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary.Add(“Delhi”, 1);
myDictionary.Add(“Mumbai”, 2);

Leave a Comment

RSS
YouTube
YouTube
Instagram