Generic Collections in C#

In c#, generic collections will enforce a type safety so we can store only the elements which is having same data type and these are provided by System.Collections.Generic namespace.

 

In previous chapter, we learned about collections in c# and these are useful to store an elements of different data types but the problem with collections is while retrieving an elements we need to perform a typecasting (boxing and unboxing) and it will effect application performance so to solve this problem c# introduced a generic collections with System.Collections.Generic namespace.

 

In c#, generic collections are the strongly typed objects so it will allow only same data type elements to store  and it doesn’t required any type casting (boxing and unboxing) while storing and retrieving an elements so performance will be improved.

 

Following are the different type of generic collection classes which are provided by System.Collections.Generic namespace.

 

ClassDescription
List It is used to represent a list of objects that can be accessed by index.
Queue It is used to represent a FIFO (First in, First Out) collection of objects.
Stack It is used to represent a LIFO (Last in, First Out) collection of objects.
SortedList<K,V> It is used to represent a collection of key/value pairs that are sorted by a key.
Dictionary<K,V> It is used to represent a collection of key/value pairs that are organized based on the key.
Hashset It is used to store a non-duplicate elements.