Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. C#
  4. Understanding Collections in C#: List, Dictionary, Queue, and Stack

Understanding Collections in C#: List, Dictionary, Queue, and Stack

Date- Mar 16,2026 65
c# collections

Overview of Collections

Collections in C# are specialized data structures that store and organize data in various ways. They provide a way to group related objects and enable various operations such as adding, removing, or searching for items. Understanding collections is crucial for efficient data manipulation and is foundational for effective programming in C#.

Prerequisites

  • Basic knowledge of C# syntax
  • Familiarity with object-oriented programming concepts
  • Understanding of data types and structures
  • Visual Studio or any C# development environment

List Collection

The List collection in C# is a dynamic array that can grow or shrink as needed. It stores elements in a sequential order and provides methods for adding, removing, and accessing items.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List fruits = new List();  // Step 1: Create a new list of strings.
        fruits.Add("Apple");                      // Step 2: Add "Apple" to the list.
        fruits.Add("Banana");                     // Step 3: Add "Banana" to the list.
        fruits.Add("Cherry");                     // Step 4: Add "Cherry" to the list.

        Console.WriteLine("Fruits in the list:"); // Step 5: Print a message to the console.
        foreach (string fruit in fruits)          // Step 6: Loop through each fruit in the list.
        {
            Console.WriteLine(fruit);          // Step 7: Print each fruit.
        }
    }
}

This code snippet demonstrates how to create a list of strings named fruits. We first instantiate the list and then add three fruit names to it. Finally, we loop through the list and print each fruit to the console.

Dictionary Collection

A Dictionary is a collection that stores key-value pairs. Each key must be unique, and it allows for quick lookups based on the key.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary ageDictionary = new Dictionary(); // Step 1: Create a new dictionary.
        ageDictionary["Alice"] = 30;       // Step 2: Add a key-value pair for Alice.
        ageDictionary["Bob"] = 25;         // Step 3: Add a key-value pair for Bob.
        ageDictionary["Charlie"] = 35;     // Step 4: Add a key-value pair for Charlie.

        Console.WriteLine("Ages:"); // Step 5: Print a message to the console.
        foreach (var entry in ageDictionary) // Step 6: Loop through each key-value pair.
        {
            Console.WriteLine($"{entry.Key}: {entry.Value}"); // Step 7: Print the key and value.
        }
    }
}

In this example, we create a dictionary called ageDictionary that maps names to their corresponding ages. We add three entries and then print each name along with its age using a loop.

Queue Collection

A Queue is a collection that follows the First In First Out (FIFO) principle. It is useful when you need to process items in the order they were added.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Queue tasks = new Queue(); // Step 1: Create a new queue.
        tasks.Enqueue("Task 1");                  // Step 2: Add Task 1 to the queue.
        tasks.Enqueue("Task 2");                  // Step 3: Add Task 2 to the queue.
        tasks.Enqueue("Task 3");                  // Step 4: Add Task 3 to the queue.

        Console.WriteLine("Processing tasks:"); // Step 5: Print a message to the console.
        while (tasks.Count > 0)                   // Step 6: Process the tasks until the queue is empty.
        {
            string currentTask = tasks.Dequeue(); // Step 7: Remove the next task from the queue.
            Console.WriteLine(currentTask);       // Step 8: Print the current task.
        }
    }
}

Here, we create a queue named tasks and add three tasks to it. We then process each task in the order they were added, demonstrating the FIFO nature of the queue.

Stack Collection

A Stack is a collection that follows the Last In First Out (LIFO) principle. It is ideal for scenarios where you need to access the most recently added item first.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Stack history = new Stack(); // Step 1: Create a new stack.
        history.Push("Page 1");                    // Step 2: Add Page 1 to the stack.
        history.Push("Page 2");                    // Step 3: Add Page 2 to the stack.
        history.Push("Page 3");                    // Step 4: Add Page 3 to the stack.

        Console.WriteLine("Navigating back:"); // Step 5: Print a message to the console.
        while (history.Count > 0)                 // Step 6: Go back through the history until the stack is empty.
        {
            string lastPage = history.Pop();    // Step 7: Remove the last page from the stack.
            Console.WriteLine(lastPage);        // Step 8: Print the last page.
        }
    }
}

This example illustrates how to create a stack named history and push three pages onto it. We then pop each page off the stack, showing the LIFO behavior.

Best Practices and Common Mistakes

  • Choose the right collection: Always select the appropriate collection type. For example, use a List for ordered data, a Dictionary for key-value pairs, a Queue for FIFO operations, and a Stack for LIFO operations.
  • Be mindful of performance: Different collections have varying performance characteristics. For instance, searching in a List is O(n), while in a Dictionary it is O(1).
  • Handle exceptions: When accessing elements, especially in a Queue or Stack, ensure to check if the collection is empty to avoid exceptions.
  • Use generics: Prefer using generic collections (e.g., List, Dictionary) for type safety and performance benefits.

Conclusion

In this post, we explored four essential collections in C#: List, Dictionary, Queue, and Stack. Each collection has its unique characteristics and use cases, making them valuable tools for managing data effectively. Remember to choose the right collection based on your specific requirements and to follow best practices to avoid common pitfalls.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Understanding Java Collections Framework: List, Set, and Map
Mar 16, 2026
Understanding Records and Pattern Matching in C# 9 and Above
Mar 16, 2026
Understanding Extension Methods in C#: Enhancing Your Code with Ease
Mar 16, 2026
Understanding Generics in C#: A Comprehensive Guide
Mar 16, 2026
Previous in C#
Understanding Generics in C#: A Comprehensive Guide
Next in C#
Mastering Exception Handling in C#: A Comprehensive Guide
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    HTTP Error 500.32 Failed to load ASP NET Core runtime 6,938 views
  • 2
    Error-An error occurred while processing your request in .… 11,272 views
  • 3
    Comprehensive Guide to Error Handling in Express.js 235 views
  • 4
    ConfigurationBuilder does not contain a definition for Set… 19,459 views
  • 5
    Mastering JavaScript Error Handling with Try, Catch, and F… 161 views
  • 6
    Mastering Unconditional Statements in C: A Complete Guide … 21,497 views
  • 7
    Unable to connect to any of the specified MySQL hosts 6,232 views

On this page

🎯

Interview Prep

Ace your C# interview with curated Q&As for all levels.

View C# Interview Q&As

More in C#

  • Zoom C# Wrapper Integration 12905 views
  • Convert HTML String To Image In C# 11510 views
  • The report definition is not valid or is not supported by th… 10880 views
  • Replacing Accent Characters with Alphabet Characters in CSha… 9871 views
  • Get IP address using c# 8700 views
View all C# posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor