Generic Collections in C#

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

 

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

 

In c#, generic collections are the strongly typed objects. It will allow only the same data type elements to store, and it doesn’t require any typecasting (boxing and unboxing) while storing and retrieving elements so that 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 useful to represent a list of objects that can be accessed by an index.
Queue It is useful to represent a FIFO (First In, First Out) collection of objects.
Stack It is useful to represent a LIFO (Last In, First Out) collection of objects.
SortedList<K, V> It is useful to represent a collection of key/value pairs that are sorted by a key.
Dictionary<K, V> It is useful to represent a collection of key/value pairs organized based on the key.
HashSet It is useful to store non-duplicate elements.