9️⃣ C# Advanced Concepts
Estimated reading: 3 minutes 29 views

🚀 C# Collections – Store and Manage Groups of Objects


🧲 Introduction – Why Use Collections in C#

C# collections provide flexible, dynamic data structures to store, organize, and manage groups of objects. From simple lists to powerful dictionaries and sets, collections simplify data manipulation and traversal in both small and enterprise-scale applications.

🎯 In this guide, you’ll learn:

  • What collections are and why they’re useful
  • Types of collections in C#: generic vs non-generic
  • Common collection classes with examples
  • Best practices and performance tips

🔍 Core Concept – What Are Collections?

A collection in C# is a class or data structure that stores multiple items as a group. Unlike arrays, collections are resizable, and many offer features like key-value access, sorting, and LINQ integration.


🧰 Types of Collections

🔹 Generic Collections (System.Collections.Generic)

TypeDescription
List<T>Dynamic array of items of type T
Dictionary<TKey, TValue>Key-value pair storage
HashSet<T>Stores unique elements only
Queue<T>FIFO (First-In-First-Out) collection
Stack<T>LIFO (Last-In-First-Out) collection
SortedList<TKey, TValue>Sorted key-value pairs

✅ Type-safe and high performance.


🔸 Non-Generic Collections (System.Collections)

TypeDescription
ArrayListDynamic array, can hold any type
HashtableKey-value pairs, not type-safe
QueueNon-generic version of Queue<T>
StackNon-generic version of Stack<T>

⚠️ Less type-safe and slower than generics.


💻 Code Example – Using List

using System;
using System.Collections.Generic;

class CollectionExample
{
    static void Main()
    {
        List<string> names = new List<string>();
        names.Add("Alice");
        names.Add("Bob");

        foreach (string name in names)
        {
            Console.WriteLine(name);
        }
    }
}

📤 Output:

Alice  
Bob

🔄 Code Example – Dictionary<TKey, TValue>

Dictionary<int, string> users = new Dictionary<int, string>();
users[1] = "John";
users[2] = "Jane";

Console.WriteLine(users[1]);  // Output: John

✅ Perfect for fast lookups by unique keys.


🧩 Choosing the Right Collection

Use CaseRecommended Collection
Store items in orderList<T>
Store unique itemsHashSet<T>
Key-based lookupsDictionary<TKey, TValue>
FIFO processingQueue<T>
LIFO processingStack<T>
Ordered mapSortedList<TKey, TValue>

💡 Tips, Pitfalls & Best Practices

💡 Tip: Prefer generic collections for type safety and better performance.

⚠️ Pitfall: Avoid modifying collections while iterating over them — it causes runtime errors.

📘 Best Practice: Use ContainsKey or TryGetValue with dictionaries to safely access values.


📌 Summary – Recap & Next Steps

C# collections offer powerful tools to work with groups of objects efficiently. Whether you need order, uniqueness, or key-based access, there’s a collection that fits the task.

🔍 Key Takeaways:

  • Collections store multiple values in structured forms
  • Generic collections (List<T>, Dictionary<TKey, TValue>) are recommended
  • Each collection serves specific scenarios: order, uniqueness, key-value

⚙️ Next: Dive into LINQ, foreach loops, and custom collection classes.


❓ FAQ – C# Collections

❓ What is the difference between List and Array?
✅ Arrays have fixed size, Lists are dynamic and grow automatically.

❓ When should I use Dictionary instead of List?
✅ Use Dictionary when you need to access items by a key instead of index.

❓ Are collections thread-safe?
❌ By default, no. Use concurrent collections (ConcurrentDictionary, etc.) for thread safety.

❓ Can I use LINQ with collections?
✅ Yes! All generic collections support LINQ queries like Where(), Select(), etc.

❓ What is the difference between HashSet and List?
HashSet stores unique items only, List allows duplicates.


Share Now :

Leave a Reply

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

Share

🚀 C# Collections

Or Copy Link

CONTENTS
Scroll to Top