🚀 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
)
Type | Description |
---|---|
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
)
Type | Description |
---|---|
ArrayList | Dynamic array, can hold any type |
Hashtable | Key-value pairs, not type-safe |
Queue | Non-generic version of Queue<T> |
Stack | Non-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 Case | Recommended Collection |
---|---|
Store items in order | List<T> |
Store unique items | HashSet<T> |
Key-based lookups | Dictionary<TKey, TValue> |
FIFO processing | Queue<T> |
LIFO processing | Stack<T> |
Ordered map | SortedList<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 :