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 comes under System.Collection namespace.

List - An array does not allow dunamic resize, but a list allow 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 number of item available in current list.

ArrayList - ArrayList stores data of object type.

You may find 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 operation , Push and Pop.
Queue - Queue works on FIFO i.e. First in First Out.

Dictionary - is a collection with key and value pairs. Each item in hashtable is

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

Comments

Popular

C# 6.0 New Features

SharePoint Interview Questions and Answers

Calling ASP.Net WebMethod using jQuery AJAX

What is Cloud Computing - A guide for beginners