An Ultimate One-Stop Solution Guide to Collections in C# Programming With Examples

Many applications need the creation and management of groups of linked items. Items may be grouped in two ways: by generating arrays of objects or collections of objects. In terms of Data Structures, collections mimic the Array Data Structures; the main difference is that, unlike arrays, collections do not require a minimum size to be specified.

In this 'Collections in C#' tutorial, you will learn the major technical aspects of Collections and the implement generic and non-generic Collections.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What Are Collections in C#?

C# collections are made to more effectively organize, store, and modify comparable data. Adding, deleting, discovering, and inserting data into the collection are all examples of data manipulation. These classes support stacks, queues, lists, and hash tables. Most collection classes implement the same interfaces.

There are several applications for collection classes, such as dynamic memory allocation for elements and index-based access to lists of objects. These classes construct collections of objects of the Object class, the building blocks of all other C# data types.

Now that we have a brief knowledge of Collections in C#, let's go over the Types of Collections. 

What Are the Types of Collections in C#?

Collections-in-C#

Collections are majorly classified into two types.

  1. Generic Collections
  2. Non-Generic Collections

Now let's discuss Generic Collections in Detail.

Our Free Courses with Certificate

Introduction to C#Enroll Now
Introduction to Front End DevelopmentEnroll Now!
C Programming BasicsEnroll Now!
JavaScript for BeginnersEnroll Now!
Introduction to C++Enroll Now!

Generic Collections

A Generic collection provides the type safety without derivation from a basic collection type and the implementation of type-specific members. The Generic Collection classes are found in the namespace "System.Collections.Generics." Internally, Generic Collections store elements in arrays of their respective types.

Generic collections are often classified into five types.

List:

In Generic List, we have to specify a data type to its contents, and all elements will have the same datatype.

Code:

using System;

using System.Collections.Generic;

namespace genericList

{

    class Program

    {

        static void Main(string[] args)

        {

            List<int> GenericList = new List<int>();

            GenericList.Add(30);

            GenericList.Add(60);

            GenericList.Add(90);

            GenericList.Add(120);

            foreach (int x in GenericList)

            {

                Console.WriteLine(x);

            }

        }

    }

}

Collections-in-C#-Article-GenericList-img1

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Dictionary:

Dictionaries usually store data in key-value pairs, and we have to specify both data types beforehand.

Code:

using System;

using System.Collections.Generic;

namespace genericDictionary

{

    class Program

    {

        static void Main(string[] args)

        {

            Dictionary<int, string> GenericDictionary = new Dictionary<int, string>();

            GenericDictionary.Add(1, "Soda");

            GenericDictionary.Add(2, "Burger");

            GenericDictionary.Add(3, "Fries");

            GenericDictionary.Add(4, "Onion Rings");

            foreach (KeyValuePair<int, string> kvp in GenericDictionary)

            {

                Console.WriteLine(kvp.Key + " " + kvp.Value);

            }  

        }

    }

}

-Article-GenericDictionary-img1

Sorted List:

A sorted list also stores a key-value pair and automatically sorts its elements in ascending order based on their keys. In the generic Sorted list, we have to specify the datatypes of its content beforehand.

Code:

using System;

using System.Collections.Generic;

namespace genericSortedList

{

    class Program

    {

        static void Main(string[] args)

        {

         SortedList<string, string> GenericSortedList = new SortedList<string, string>();

            GenericSortedList.Add("American", "Burger");

            GenericSortedList.Add("Lime", "Soda");

            GenericSortedList.Add("French", "Fries");

            GenericSortedList.Add("Onion", "Rings");

            foreach (KeyValuePair<string, string> kvp in GenericSortedList)

            {

                Console.WriteLine(kvp.Key + " " + kvp.Value);

            }

        }

    }

}

C#-Article-GenericSortedList-img1

Stack:

Values are kept in Stack using LIFO (Last In First Out). It offers the Push() and Pop() & Peek() methods to add and retrieve values, respectively. In generic Stack, we have to specify the datatypes of its content beforehand.

Code:

using System;

using System.Collections.Generic;

namespace genericStack

{

    class Program

    {

        static void Main(string[] args)

        {

            Stack<string> steak = new Stack<string>();

            steak.Push("Rare");

            steak.Push("Medium Rare");

            steak.Push("Medium");

            steak.Push("Well done");

            foreach (string s in steak)

            {

                Console.WriteLine(s);

            }

        }

    }

}

Article-GenericStack-img1

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Queue:  

Values are kept in a queue in a FIFO fashion (First In, First Out). The sequence in which the values were inserted is preserved. It offers the Enqueue() and Dequeue() methods to add and remove values from the collection. In the generic queue, we have to specify the datatypes of its content beforehand.

Code:

using System;

using System.Collections.Generic;

namespace genericQueue

{

    class Program

    {

        static void Main(string[] args)

        {

            Queue<string> GenericQueue = new Queue<string>();

                GenericQueue.Enqueue("Mark");

              GenericQueue.Enqueue("Bill");

                GenericQueue.Enqueue("Xavier");

                GenericQueue.Enqueue("Michael");

                foreach (string s in GenericQueue)

                {

                    Console.WriteLine(s);

                }

        }

    }

}

Article-GenericQueue-img1

Now that we have successfully implemented the generic collections. Let's go over the non-generic collections.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Non-Generic Collections

Non-generic collections are specialized data storage and retrieval classes that handle stacks, queues, lists, and hash tables. The "System.Collections" namespace contains the Non-generic Collection classes. Non-generic collections store elements in object arrays internally, allowing them to hold any data type.

Non-Generic collections are often classified into five types.

ArrayList:

The array's size might change during use since it is dynamic, which implies it is not static. It offers functions that are comparable to those in the generic List class.

Code:

using System;

using System.Collections;

namespace nonGenericArrayList

{

    class Program

    {

        static void Main(string[] args)

        {

            ArrayList NonGenericArrayList = new ArrayList();

            string str = "Like, Share, Subscribe";

            int x = 11;

            DateTime d = DateTime.Parse("3-dec-1998");

            NonGenericArrayList.Add(str);

            NonGenericArrayList.Add(x);

            NonGenericArrayList.Add(d);

            foreach (object o in NonGenericArrayList)

            {

                Console.WriteLine(o);

            }

        }

    }

}

Article-NonGenericArrayList-img1.

HashTable:

A hash table data structure is made up of key-value pairs. The hash values of the keys are compared to find the values. It offers functions that are comparable to those in the generic dictionary class.

Code:

using System;

using System.Collections;

namespace nonGenericHashTable

{

    class Program

    {

        static void Main(string[] args)

        {

            Hashtable NonGenericHashTable = new Hashtable();

            NonGenericHashTable.Add(1, "Soda");

            NonGenericHashTable.Add(2, "Burger");

            NonGenericHashTable.Add(3, "Fries");

            NonGenericHashTable.Add(4, "Onion Rings");

            foreach (DictionaryEntry h in NonGenericHashTable)

            {

                Console.WriteLine (h.Key + " " + h.Value);

            }

        }

    }

}

Article-NonGenericHashTable-img1

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Sorted List:

It is similar to the generic Sorted list, except we don't have to specify specific data type.

Code:

using System;

using System.Collections;

namespace nonGenericSortedList

{

    class Program

    {

        static void Main(string[] args)

        {

            SortedList NonGenericSortedList = new SortedList();

            NonGenericSortedList.Add("American", "Burger");

            NonGenericSortedList.Add("Lime", "Soda");

            NonGenericSortedList.Add("French", "Fries");

            NonGenericSortedList.Add("Onion", "Rings");

            foreach (DictionaryEntry d in NonGenericSortedList)

            {

                Console.WriteLine(d.Key + " " + d.Value);

            }

        }

    }

}

Article-NonGenericSortedList-img1

Stack:

It's a FIFO (first-in, first-out) list. Hence it works similarly to the Stack class in generic collections.

Code:

using System;

using System.Collections;

namespace nonGenericStack

{

    class Program

    {

        static void Main(string[] args)

        {

            Stack steak = new Stack();

            steak.Push("Rare");

            steak.Push("Medium Rare");

            steak.Push("Medium");

            steak.Push("Well done");

            foreach (object o in steak)

            {

            Console.WriteLine(o);

            }

        }

    }

}

Article-NonGenericStack-img1.

Master Core Java 8 Concepts, Java Servlet & More!

Java Certification TrainingENROLL NOW
Master Core Java 8 Concepts, Java Servlet & More!

Queue:  

A first-in, first-out collection of items is represented by it. When you require first-in, first-out access to objects, you utilize it. It offers functions that are comparable to those in the generic Queue collection.

Code:

using System;

using System.Collections;

namespace nonGenericQueue

{

    class Program

    {

        static void Main(string[] args)

        {

            Queue NonGenericQueue = new Queue();

            NonGenericQueue.Enqueue("Mark");

            NonGenericQueue.Enqueue("Bill");

            NonGenericQueue.Enqueue("Xavier");

            NonGenericQueue.Enqueue("Michael");

            foreach (object o in NonGenericQueue)

            {

                Console.WriteLine(o);

            }

        }

    }

}

Article-NonGenericQueue-img1.

Now that we have discussed the collections and their types let's go over various benefits of collections in C#.

Benefits of Collections in C#

There are many benefits of Collections in C#.

  • Generic collections work faster than non-generic ones and decrease exceptions by revealing compile-time faults.
  • Non-generic collection types are in "System. Collections," while generic types are in "System.Collections.Generic."
  • C# also has several specialized collections tuned to deal with a specific data type, which we can find in the "System.Collections.Specialized" namespace.
  • The Collection class supports null as a valid reference type value and enables redundant elements.

Till now, you have a good command of the technical and theoretical aspects of Collections and their various types.

Accelerate your career as a skilled MERN Stack Developer by enrolling in a unique Full Stack Developer - MERN Stack Master's program. Get complete development and testing knowledge on the latest technologies by opting for the MERN Stack Developer Course. Contact us TODAY!

Next Steps

You can start with "Streams in C#" as your next Chapter in your path to conquering C# Programming. A stream is an organized sequence of bytes transmitted from one application or input device to another. These bytes are transmitted and read sequentially and always arrive in the same sequence as they were sent.

You can take on various programming tasks now that you have a solid understanding of these effective data organization methods. Recall that the examples discussed here are from the very beginning. Don't be afraid to try new things and use your newly acquired expertise in your projects.

Do you want to improve your C# abilities even more? Take into account signing up for a course called Full Stack Developer - MERN Stack. With this extensive curriculum's help, you can create dynamic web applications where collections are essential for organizing and modifying data. So get in and start learning about the fascinating field of full-stack development!

You can utilize our Comment Section Below for your queries regarding our "Collections in C#" tutorial. Happy learning!

About the Author

Vaibhav KhandelwalVaibhav Khandelwal

Vaibhav Khandelwal is a proactive tech geek who's always on the edge of learning new technologies. He is well versed in competitive programming and possesses sound knowledge of web development. He likes to read fictional and sci-fi novels and likes to play strategy games like chess

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.