Collections in C#

| By Webner

Collections in C#

Arrays are useful for creating and working with a fixed number of strongly typed objects.

Problem with Arrays:
1. Fixed length
2. Insert similar data type elements

Collections are used to create and manage groups of related objects by creating a Collection of objects. The group of objects you work with can grow and shrink dynamically as needed for the application.

In C# collections are divided into several classes :
1. System.Collections.Generic
2. System.Collection
3. System.Collections.Concurrent

The generic collections are found under System.Collections.Generic namespace.
These collections include Dictionary<T, T>, List<T>, Queue<T>, SortedList<T>, and Stack<T>.
It allows you to define type-safe data structures. Type-safe data means the compiler will validate the data types while compiling, and throw an error if you try to assign the wrong type to a variable. It holds the elements of the same data types.


// Generic collection using List<T> 
using System; 
using System.Collections.Generic; 

class GenericExample{ 

		public static void Main(String[] args)  // Main Method 

	         List<int> data= new List<int>();  // Creating a List of integers 

		for (int j = 2; j < 5; j++) // adding items in data
			data.Add(j * 2); 

		// Displaying items of data

		foreach(int items in data) 

Non-Generic collection in C# is defined in System. Collections namespace. These collections include ArrayList, SortedList, Stack, Queue and HashTable. This collection holds the elements of different data types which means as an object type so that it includes the overhead of type conversions.


using System; 
using System.Collections; 

class NonGeneric{ 
	public static void Main() 
                     // Creating an ArrayList 
		ArrayList data= new ArrayList(); 

		// Adding elements to ArrayList 
	} } 

It provides thread-safe and scalable collection classes so it can be accessed by multiple threads at a time (Multithreading). whenever multiple threads are accessing the collection concurrently it can efficiently add or remove items in the collections, without any additional synchronization in user code and can be used in place of System.Collections.NonGeneric and System.Collections. This include ConcurrentStack<T>, ConcurrentQueue<T>, BlockingCollection<T>, ConcurrentBag<T> etc.


using System;
using System.Collections.Concurrent;

class ConcurrentDemo
    static void Main ()
       int[] ints = { 1, 2, 3 }; 
      ConcurrentStack<int> stack = new ConcurrentStack<int>();
      stack.PushRange(ints); //add multiple items into stack

Leave a Reply

Your email address will not be published. Required fields are marked *