Collections in C Sharp (C#)
In c#, the collection is a class that is useful to manage a group of objects in a flexible manner to perform various operations like insert, update, delete, get, etc. on the object items in a dynamic manner based on our requirements. Generally, while working in c# applications we will get a requirement like to create or manage a group of related objects. In that case, we have two ways to create group objects in c# i.e. by using the arrays and collections. We can use arrays in c# but those are useful only when we are working with a fixed number of strongly-typed objects.
So, to solve this problem Microsoft has introduced Collections in c# to work with a group of objects which can grow or shrink dynamically based on our requirements.
In c#, the collection is a class so we just need to declare an instance of the class before we perform any operations like add, delete, etc.
on the defined collection and the collections are implemented by using the IEnumerable
interface so we can access collection items by using a foreach loop.
C# Collection Types
In c#, we have a different type of collection classes are available, those are
System.Collections
)System.Collections.Generic
)System.Collections.Concurrent
: Available from .NET Framework 4 )C# Non-Generic Collections
In c#, non-generic collection classes are useful to store elements of different data types and these are provided by System.Collections
namespace. Now, these collection classes are legacy types so whenever possible try to use generic collections (System.Collections.Generic
) or concurrent collections (System.Collections.Concurrent).
Following are the different type of non-generic collection classes which are provided by System.Collections
namespace.
C# Generic Collections
In c#, generic collections will enforce a type safety so we can store only the elements which are having the same data type and these are provided by System.Collections.Generic
namespace.
Following are the different type of generic collection classes which are provided by System.Collections.Generic
namespace.
C# Concurrent Collections
In c#, concurrent collections are useful to access collection items from multiple threads and these are available from .NET Framework 4 with System.Collections.Concurrent namespace.
In case, if we are using multiple threads to access a collection concurrently, then we need to use concurrent collections instead of non-generic
and generic collections
.
Following are the different type of concurrent collection classes which are provided by System.Collections.Concurrent
namespace.