Technical interview Q&A plus 100+ career & HR questions—notice period, salary negotiation, resume, LinkedIn, freelancing, AI careers, and behavioral interviews with detailed, real-world answers.
C# Collections C# Programming Tutorial · Collections
Generic collections are type-safe and defined using generics (<T>), allowing you to specify
the type of elements they hold. This ensures compile-time type checking and eliminates the
need for casting.
Non-generic collections, on the other hand, store elements as objects (object type),
requiring boxing/unboxing for value types and casting for reference types.
Example:
// Generic collection
List<int> numbers = new List<int>();
numbers.Add(10); // No boxing, type-safe
// Non-generic collection
rrayList list = new ArrayList();
list.Add(10); // Boxing occurs
int value = (int)list[0]; // Needs casting
Real-world use case:
In applications dealing with specific data types (e.g., a list of customer IDs), generic
collections are ideal. Non-generic collections may be used in legacy systems or when
dealing with multiple data types.
C# Collections C# Programming Tutorial · Collections
A Dictionary<TKey, TValue> is a generic collection in C# that stores data as
key-value pairs. It provides fast lookup, addition, and removal of values based on their
keys.
Example:
Dictionary<string, int> ages = new Dictionary<string, int>();
ges.Add("Alice", 30);
ges.Add("Bob", 25);
Use case: Storing user profiles by ID, or mapping product names to prices.
C# Collections C# Programming Tutorial · Collections
A Queue<T> is a generic collection in C# that stores elements in a First-In, First-Out
(FIFO) order.
Use case:
Modeling real-world queues — e.g., print jobs, task scheduling, or customer service
systems.
Example:
Queue<string> orders = new Queue<string>();
orders.Enqueue("Order1");
orders.Enqueue("Order2");
C# Collections C# Programming Tutorial · Collections
A Stack<T> is a generic collection in C# that stores elements in a Last-In, First-Out
(LIFO) order.
Real-world use case:
Undo operations, browser history, expression evaluation.
Example:
Stack<int> numbers = new Stack<int>();
numbers.Push(10);
numbers.Push(20); // Top of the stack
C# Collections C# Programming Tutorial · Collections
HashSet<T> is a generic collection that stores unique elements with no particular order.
It is optimized for fast lookups, additions, and deletions.
Use case:
When you want to store a collection of unique items without duplicates, such as user IDs,
tags, or keywords.
HashSet<int> uniqueNumbers = new HashSet<int> { 1, 2, 3 };
uniqueNumbers.Add(4);
C# Collections C# Programming Tutorial · Collections
LinkedList<T> is a doubly linked list collection in C#. It stores elements as nodes,
where each node contains the data and references to the previous and next nodes.
Example:
LinkedList<int> numbers = new LinkedList<int>();
numbers.AddLast(10);
numbers.AddLast(20);
C# Collections C# Programming Tutorial · Collections
SortedList<TKey, TValue> is a collection of key-value pairs that maintains the
elements sorted by keys.
IList<KeyValuePair<TKey, TValue>>.
or a provided comparer.
Example:
SortedList<int, string> sortedList = new SortedList<int, string>();
sortedList.Add(3, "Three");
sortedList.Add(1, "One");
sortedList.Add(2, "Two");
The elements are stored sorted by key: 1, 2, 3.
C# Collections C# Programming Tutorial · Collections
SortedSet<T> is a collection that stores unique elements in sorted order.
Example:
SortedSet<int> sortedSet = new SortedSet<int> { 5, 1, 3 };
sortedSet.Add(2); // Sorted order maintained: {1, 2, 3, 5}
C# Collections C# Programming Tutorial · Collections
Collection initializers allow you to create and populate a collection in a concise way at the
time of declaration.
Example:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
Dictionary<string, int> ages = new Dictionary<string, int>
{
{ "Alice", 30 },
{ "Bob", 25 }
};
This syntax internally calls the collection’s Add() method for each element.
C# Collections C# Programming Tutorial · Collections
List<T> is a generic collection in C# that represents a dynamically sized list of elements.
It resides in the System.Collections.Generic namespace and grows or shrinks as
needed.
Use it when:
Example:
List<string> names = new List<string>();
names.Add("Alice");
C# Collections C# Programming Tutorial · Collections
Answer: List<string> fruits = new List<string> { "Apple", "Banana" }; foreach (var fruit in fruits) { Console.WriteLine(fruit); }
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
ConcurrentDictionary<TKey, TValue> is a thread-safe dictionary designed for
concurrent access by multiple threads without needing external synchronization (locks).
Example:
ConcurrentDictionary<int, string> concurrentDict = new
ConcurrentDictionary<int, string>();
concurrentDict.TryAdd(1, "One");
concurrentDict.TryUpdate(1, "Uno", "One");
C# Collections C# Programming Tutorial · Collections
LinkedList<T> is a doubly linked list collection in C#. It stores elements as nodes,
where each node contains the data and references to the previous and next nodes.
Example:
LinkedList<int> numbers = new LinkedList<int>();
numbers.AddLast(10);
numbers.AddLast(20);
C# Collections C# Programming Tutorial · Collections
ccurately.
deeper insights.
multiple times and averaging results.
Example:
var stopwatch = Stopwatch.StartNew();
list.Add(1000);
stopwatch.Stop();
Console.WriteLine($"Add operation took {stopwatch.ElapsedTicks}
ticks");
C# Collections C# Programming Tutorial · Collections
To implement a custom collection:
interfaces such as ICollection<T>, IEnumerable<T>, or IList<T>.
GetEnumerator(), and indexers.
Example:
public class MyCustomCollection<T> : Collection<T>
{
protected override void InsertItem(int index, T item)
{
// Custom validation
if (item == null) throw new
rgumentNullException(nameof(item));
base.InsertItem(index, item);
}
}C# Collections C# Programming Tutorial · Collections
Generic collections offer several advantages:
Example:
List<string> names = new List<string>();
names.Add("Alice"); // Valid
// names.Add(123); // Compile-time error
Real-world use case:
When managing a list of product names or order numbers, using List<string> or
List<int> ensures that invalid data types are caught at compile time.C# Collections C# Programming Tutorial · Collections
Answer: Use the Add() method or the indexer []: // Using Add() dictionary.Add("key1", "value1"); // Using indexer dictionary["key2"] = "value2"; Note: Add() throws an exception if the key already exists, while indexer will overwrite the value.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Internally, Queue<T> uses a circular array to efficiently manage memory and operations.
This implementation ensures constant time operations for enqueue and dequeue.
C# Collections C# Programming Tutorial · Collections
Internally, Queue<T> uses a circular array to efficiently manage memory and operations.
This implementation ensures constant time operations for enqueue and dequeue.
C# Collections C# Programming Tutorial · Collections
Internally, Stack<T> uses an array-based dynamic storage system:
doubles)
This structure provides fast push and pop operations (constant time on average).
C# Collections C# Programming Tutorial · Collections
clear, allowing easy customization.
extensibility.
validation, event firing).
C# Collections C# Programming Tutorial · Collections
Feature HashSet<T> List<T> Dictionary<TKey,
TValue>
llows
duplicates?
No Yes Keys: No; Values: Yes
Order No guaranteed
order
Maintains insertion
order
No guaranteed order
Lookup speed O(1) average O(n) O(1) average for keys
Key-value pairs No (only values) No Yes (key-value pairs)
C# Collections C# Programming Tutorial · Collections
Answer: Use AddFirst(value) to add at the start. Use AddLast(value) to add at the end. numbers.AddFirst(5); // Adds 5 at the beginning numbers.AddLast(30); // Adds 30 at the end
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
cache-friendly.
Previous), leading to more memory overhead.
performance than LinkedList<T>, especially for large collections.
C# Collections C# Programming Tutorial · Collections
Feature SortedList<TKey, TValue> Dictionary<TKey, TValue>
Order Maintains keys in sorted order No guaranteed order
Internal storage Uses two arrays (keys &
values)
Uses a hash table
Lookup complexity O(log n) (binary search) O(1) average
Insertion complexity O(n) (due to shifting elements) O(1) average
Memory overhead Lower (arrays) Higher (hash buckets,
overhead)
C# Collections C# Programming Tutorial · Collections
Feature SortedSet<T> HashSet<T>
Ordering Maintains sorted order No guaranteed order
Implementation Balanced binary search tree Hash table
Lookup
complexity
O(log n) O(1) average
Memory
overhead
Higher (tree nodes) Lower (hash buckets)
Use case When sorted data or range
queries needed
Fast insertion and lookup without
ordering
C# Collections C# Programming Tutorial · Collections
Feature ConcurrentQueue<T> Queue<T>
Thread safety Designed for concurrent access Not thread-safe; requires locks
Locking
mechanism
Internal lock-free or fine-grained
locking
No internal synchronization
Suitable for Multi-threaded
producer-consumer patterns
Single-threaded scenarios or
external synchronization
ConcurrentQueue<T> allows safe enqueueing and dequeueing by multiple threads
simultaneously without corrupting the data.
C# Collections C# Programming Tutorial · Collections
LINQ itself doesn’t modify collections directly but produces new collections based on
queries.
You typically combine LINQ with collection methods to add elements, for example:
var evenNumbers = new List<int> { 2, 4, 6 };
var allNumbers = new List<int> { 1, 2, 3, 4, 5, 6 };
var combined = allNumbers.Where(n => n % 2 == 0).ToList(); //
Filters even numbers
If you want to add LINQ results to a collection:
List<int> filteredNumbers = allNumbers.Where(n => n % 2 ==
0).ToList();
C# Collections C# Programming Tutorial · Collections
Answer: You can use the Add() or AddRange() method. Example: List<int> numbers = new List<int>(); numbers.Add(10); // Add single item numbers.AddRange(new int[] { 20, 30 }); // Add multiple
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
for (int i = 0; i < fruits.Count; i++) { Console.WriteLine(fruits[i]); }
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
IEnumerable<T> is the base interface for all generic collections that can be enumerated
(looped over). It allows the use of foreach loops and LINQ queries.
It defines a single method:
IEnumerator<T> GetEnumerator();
Example:
List<string> items = new List<string> { "A", "B", "C" };
foreach (string item in items) // IEnumerable<string> in action
{
Console.WriteLine(item);
}
Real-world use case:
When reading product data from a list or querying a database, IEnumerable<T> allows
deferred execution and efficient data processing using LINQ.
C# Collections C# Programming Tutorial · Collections
Use methods like:
Example:
numbers.Remove(10);
numbers.RemoveAt(0);
numbers.RemoveAll(x => x > 100);
numbers.Clear();
C# Collections C# Programming Tutorial · Collections
Answer: dd: sortedList.Add(4, "Four"); Remove: sortedList.Remove(2); // Remove element with key 2 Search (by key): bool exists = sortedList.ContainsKey(3); string value = sortedList[3]; // Access value by key
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Use Remove(value) to remove the first occurrence of the specified value, or
RemoveFirst() / RemoveLast() to remove from the start or end respectively.
numbers.Remove(10); // Removes the first node with value 10
numbers.RemoveFirst(); // Removes the first node
numbers.RemoveLast(); // Removes the last node
C# Collections C# Programming Tutorial · Collections
C# Collections C# Programming Tutorial · Collections
Answer: All these operations generally have O(1) average time complexity due to the underlying hash table structure.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Example:
var products = new List<Product> { ... };
// Filter products with price > 100
var expensiveProducts = products.Where(p => p.Price > 100);
// Sort products by name
var sortedProducts = products.OrderBy(p => p.Name);
// Group products by category
var groupedProducts = products.GroupBy(p => p.Category);C# Collections C# Programming Tutorial · Collections
Method Description
Push() Adds an element to the top
Pop() Removes and returns the top element
Peek() Returns top element without removing it
Clear(
Removes all elements
Example:
stack.Push(100); // Add
int top = stack.Pop(); // Remove and return topC# Collections C# Programming Tutorial · Collections
ConcurrentQueue, BlockingCollection, etc.).
ReaderWriterLock around critical sections when using non-thread-safe
collections.
C# Collections C# Programming Tutorial · Collections
Scenario Best Choice Trade-offs
Fast indexed
ccess
List<T> Slower inserts/removes in
the middle
Frequent
insert/delete at
ends
LinkedList<T> No fast indexed access;
higher memory use
Fast lookups by
key
Dictionary<TKey, TValue> No sorted order
Sorted key-value
pairs
SortedList<TKey, TValue> or
SortedDictionary<TKey,
TValue>
Slower inserts vs
Dictionary
Thread-safe
multi-thread use
ConcurrentDictionary /
ConcurrentQueue
Slight overhead for
synchronization
C# Collections C# Programming Tutorial · Collections
Operation Method Description
dd Enqueue
()
dds an item to the end of the queue
Remove Dequeue
()
Removes and returns the item at the front
Peek Peek() Returns the front item without removing it
Example:
Queue<int> queue = new Queue<int>();
queue.Enqueue(1); // Add
int front = queue.Dequeue(); // RemoveC# Collections C# Programming Tutorial · Collections
Answer: Use the Remove(key) method: dictionary.Remove("key1"); Returns true if the key was found and removed, false otherwise.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
(used in sorting operations like Sort()).
GetHashCode(T obj) to determine equality and hashing (used in dictionaries,
sets, etc.).
beyond default implementations.
C# Collections C# Programming Tutorial · Collections
ICollection<T> extends IEnumerable<T> and adds features like:
Difference:
Example:
ICollection<int> numbers = new List<int>();
numbers.Add(5);
numbers.Remove(5);
Console.WriteLine(numbers.Count);
Real-world use case:
Use ICollection<T> when you need to manipulate the collection (add/remove items),
such as managing an in-memory cart of products in a shopping application.
C# Collections C# Programming Tutorial · Collections
Answer: Use a foreach loop to traverse the linked list from start to end. foreach (var num in numbers) { Console.WriteLine(num); }
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Operation Method Description
Union UnionWith() Adds all elements from another set
Intersection IntersectWit
h()
Keeps only elements present in both
sets
Difference ExceptWith() Removes elements found in another set
Example:
SortedSet<int> set1 = new SortedSet<int> { 1, 2, 3 };
SortedSet<int> set2 = new SortedSet<int> { 3, 4, 5 };
set1.UnionWith(set2); // {1, 2, 3, 4, 5}
set1.IntersectWith(set2); // {3, 4, 5} (if applied on the original
set1)
set1.ExceptWith(set2); // {1, 2} (if applied on the original
set1)
C# Collections C# Programming Tutorial · Collections
Add all elements from the collection to a HashSet<T>, which automatically removes
duplicates.
List<int> numbers = new List<int> { 1, 2, 2, 3, 3, 4 };
HashSet<int> uniqueNumbers = new HashSet<int>(numbers);
Now, uniqueNumbers contains only unique values: {1, 2, 3, 4}.
C# Collections C# Programming Tutorial · Collections
Answer: ContainsKey(key) – checks for key existence ContainsValue(value) – checks for value Example: dictionary.ContainsKey("Alice"); // true/false dictionary.ContainsValue(30); // true/false
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
expressive.
performance.
C# Collections C# Programming Tutorial · Collections
Answer: Push() → O(1) average, O(n) worst-case (if resizing needed) Pop() → O(1) These operations are fast and efficient due to the internal array structure.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Searching by key uses binary search, so the time complexity is O(log n).
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Feature BlockingCollection<T> Collection<T>
Thread safety Thread-safe for adding and taking items Not thread-safe
Blocking
behavior
Supports blocking and bounding (waits when
empty/full)
No blocking behavior
Use case Producer-consumer scenarios General-purpose
collection
dditional
features
Supports bounded capacity and cancellation Basic collection
BlockingCollection<T> wraps around other thread-safe collections and provides
blocking and bounding capabilities, ideal for producer-consumer queues.
📘 C# Collections: Performance &
Memory Considerations – Interview Q&A
C# Collections C# Programming Tutorial · Collections
List<T>(capacity)) to avoid frequent resizing.
LinkedList<T> if indexing is needed).
non-generic.
📘 C# Advanced Collection Topics –
Interview Questions & AnswersC# Collections C# Programming Tutorial · Collections
Answer: Enqueue() → O(1) average case Dequeue() → O(1) average case Due to the internal circular array and pointer arithmetic, both operations are highly efficient unless resizing is needed (which is O(n), but infrequent).
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Example (manual):
List<MyClass> DeepClone(List<MyClass> original)
{
return original.Select(item => item.Clone()).ToList();
}
Note: MyClass must implement a Clone() method that performs deep copy.
C# Collections C# Programming Tutorial · Collections
Answer: Accessing an element by index is O(1) (constant time) — same as arrays. Example: int first = numbers[0]; // O(1)
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
IList<T> extends ICollection<T> and allows:
Example:
IList<string> fruits = new List<string>();
fruits.Add("Apple");
fruits.Insert(0, "Banana"); // Insert at index 0
Console.WriteLine(fruits[1]); // Access by index
Real-world use case:
Use IList<T> when order matters and you need to access, insert, or remove elements at
specific positions, like reordering tasks in a to-do list.
C# Collections C# Programming Tutorial · Collections
Example:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class EmployeeCollection : Collection<Employee>
{
// You can add custom methods specific to Employee collection
here
}
Or simply use List<Employee> directly for flexibility.
C# Collections C# Programming Tutorial · Collections
Answer: Use a foreach loop which iterates over the elements in sorted ascending order: foreach (var item in sortedSet) { Console.WriteLine(item); }
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Adding or removing at the start or end: O(1) Adding or removing at an arbitrary position (if you already have the node reference): O(1) Searching for a node by value: O(n), because traversal is required
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: No, HashSet<T> does not allow duplicates. Attempting to add a duplicate value will return false and not change the set. bool added = uniqueNumbers.Add(2); // returns false because 2 lready exists
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Use the Peek() method to view the front element without removing it.
Example:
Queue<string> tasks = new Queue<string>();
tasks.Enqueue("Task1");
string nextTask = tasks.Peek(); // Returns "Task1", does not remove
it
Useful when you want to see what’s next without modifying the queue.
C# Collections C# Programming Tutorial · Collections
Answer: The average time complexity is O(1) (constant time), thanks to hash-based indexing. However, in worst-case scenarios (rare), it can degrade to O(n).
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Example:
bool hasItem = numbers.Contains(10);
int index = numbers.IndexOf(10);
var result = numbers.Find(x => x > 50);C# Collections C# Programming Tutorial · Collections
Use methods like ToList(), ToArray(), or ToDictionary() to convert LINQ query
results to different collection types.
Examples:
var numbers = new int[] { 1, 2, 3, 4, 5 };
// Convert to List<int>
List<int> numberList = numbers.ToList();
// Convert to array
int[] numberArray = numberList.ToArray();
// Convert to dictionary (key = number, value = square)
Dictionary<int, int> numberDict = numbers.ToDictionary(n => n, n =>
n * n);
📘 C# Thread-Safe Collections –
Interview Questions & AnswersC# Collections C# Programming Tutorial · Collections
Answer: Use the Peek() method. Example: int top = stack.Peek(); This is useful when you just want to inspect the top element without altering the stack.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
You can use a foreach loop over KeyValuePair<TKey, TValue> elements, which
iterates in sorted key order:
foreach (var kvp in sortedList)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
You can also iterate over keys or values separately:
foreach (var key in sortedList.Keys) { /* ... */ }
foreach (var value in sortedList.Values) { /* ... */ }
📘 C# SortedSet<T> – Interview
Questions & Answers
C# Collections C# Programming Tutorial · Collections
Answer: Method Purpose dd() Adds one item ddRange () dds multiple items (collection) Example: list.Add(1); // One item list.AddRange(new[] { 2, 3, 4 }); // Multiple
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Operation LinkedList<T> List<T>
Indexed access O(n) (no indexing) O(1) (direct access)
dd/Remove at
start/end
O(1) O(n) (start), O(1) (end)
dd/Remove in middle O(1) (with node ref) O(n) (shifts elements)
Memory overhead Higher (extra pointers) Lower (array storage)
Summary:
Use LinkedList<T> when you need fast insertions/deletions anywhere and don’t require
indexed access. Use List<T> for fast random access and better memory efficiency.
📘 C# SortedList<TKey, TValue> –
Interview Questions & AnswersC# Collections C# Programming Tutorial · Collections
These interfaces provide read-only access to collections:
Example:
IReadOnlyList<int> ids = new List<int> { 1, 2, 3 };
Console.WriteLine(ids[0]); // Access element
// ids[0] = 10; // Compile-time error – read-only
Real-world use case:
Useful in APIs where you want to expose collection data but prevent consumers from
modifying it—e.g., returning a list of supported currencies from a service.
C# Collections C# Programming Tutorial · Collections
Dictionary?
Feature TryGetValue() Indexer (dictionary[key])
Safe? Yes – avoids exception No – throws if key doesn't exist
Returns Boolean (and output
value)
Direct value
Use
case
When unsure if key exists When key is guaranteed to
exist
Example:
if (dictionary.TryGetValue("Bob", out int age)) {
Console.WriteLine(age);
}
// dictionary["Unknown"]; // throws KeyNotFoundException if missing
C# Collections C# Programming Tutorial · Collections
Answer: Due to the underlying balanced tree structure, these operations have O(log n) time complexity. 📘 C# Collection Initializers & LINQ – Interview Questions & Answers
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Union: Combines all unique elements from both sets
set1.UnionWith(set2);
set1.IntersectWith(set2);
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.UnionWith(set2); // set1 = {1, 2, 3, 4, 5}
set1.IntersectWith(set2); // set1 = {3, 4, 5}C# Collections C# Programming Tutorial · Collections
Feature TryGetValue() Indexer (dictionary[key])
Safe? Yes – avoids exception No – throws if key doesn't exist
Returns Boolean (and output
value)
Direct value
Use
case
When unsure if key exists When key is guaranteed to
exist
Example:
if (dictionary.TryGetValue("Bob", out int age)) {
Console.WriteLine(age);
// dictionary["Unknown"]; // throws KeyNotFoundException if missing
C# Collections C# Programming Tutorial · Collections
Peek() returns the top element without removing it. It’s helpful for:
Example:
if (stack.Count > 0)
{
var current = stack.Peek();
}
Throws InvalidOperationException if the stack is empty.
C# Collections C# Programming Tutorial · Collections
IComparer.
Example:
SortedList<int, string> sortedList = new SortedList<int, string>();
sortedList.Add(10, "Ten");
sortedList.Add(5, "Five");
sortedList.Add(20, "Twenty");
// Items automatically sorted by keys: 5, 10, 20
If you want to sort by custom criteria, implement an IComparer and pass it to the
SortedList constructor.
C# Collections C# Programming Tutorial · Collections
Answer: Use the Clear() method to remove all elements. Example: tasks.Clear(); fter calling Clear(), the queue is empty (Count == 0).
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: dd()? Insert(index, item) adds an item at a specific index. Add(item) adds to the end of the list. Example: list.Insert(0, 99); // Add at beginning list.Add(100); // Add at end
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Feature Non-Generic Generic
Type Safety No Yes
Performanc
Slower (boxing/unboxing) Faster
Casting Required Not required
Syntax Less readable Clean and
type-specific
Examples:
// Non-generic
rrayList arr = new ArrayList();
rr.Add(1);
rr.Add("text"); // Allowed, but risky
// Generic
List<int> list = new List<int>();
list.Add(1);
// list.Add("text"); // Compile-time error
// Hashtable vs Dictionary
Hashtable ht = new Hashtable();
ht["id"] = 101;
Dictionary<string, int> dict = new Dictionary<string, int>();
dict["id"] = 101;
Real-world use case:
Generic collections are recommended for new development due to safety and performance.
Non-generic collections are often found in older legacy systems.
C# Collections C# Programming Tutorial · Collections
Answer: Insert(index, item) adds an item at a specific index. Add(item) adds to the end of the list. Example: list.Insert(0, 99); // Add at beginning list.Add(100); // Add at end
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Example:
foreach (var key in dictionary.Keys)
Console.WriteLine(key);
foreach (var value in dictionary.Values)
Console.WriteLine(value);
C# Collections C# Programming Tutorial · Collections
Answer: Method Purpose Return Value dd(item) Adds item if not already present true if added, false if duplicate Contains(it em) Checks if item exists in the set true if found, false otherwise
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use a foreach loop. Iteration does not modify the queue. Example: foreach (var order in orders) { Console.WriteLine(order); } You can also use .ToArray() if needed: string[] items = orders.ToArray();
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use the Count property. if (stack.Count == 0) { Console.WriteLine("Stack is empty"); } Unlike some languages, C# stacks do not provide an IsEmpty property.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use the Sort() method or provide a custom comparer. Example: list.Sort(); // Default sort (ascending) list.Sort((a, b) => b.CompareTo(a)); // Descending
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Example:
dictionary.Add("John", 25);
dictionary.Add("John", 30); // Exception
dictionary["John"] = 30; // Overwrites the value safelyC# Collections C# Programming Tutorial · Collections
Answer: Again, use the Peek() method: var front = queue.Peek(); Difference from Dequeue(): Peek() returns the front element without removing it. Dequeue() returns and removes the front element. 📘 C# Stack<T> – Interview Questions &
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Feature IEnumerable
<T>
ICollection<T>
Read-only Yes No
Modification Not supported Supports Add, Remove,
Clear
Count property No Yes (Count)
Example:
IEnumerable<string> names = new List<string> { "A", "B" };
// names.Add("C"); // Error
ICollection<string> nameCollection = new List<string> { "A", "B" };
nameCollection.Add("C"); // Allowed
Real-world scenario:
Use IEnumerable<T> for read-only, query-focused tasks like LINQ. Use
ICollection<T> when managing and modifying the collection.
C# Collections C# Programming Tutorial · Collections
Answer: Use a foreach loop; the iteration order is not guaranteed. foreach (var item in uniqueNumbers) { Console.WriteLine(item); } 📘 C# LinkedList<T> – Interview Questions & Answers
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use the Clear() method to remove all elements. stack.Clear(); fter this, Count becomes 0, and the internal array is reset.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Feature List<T> ArrayList
Generic Yes No
Type Safety Compile-time Runtime (casting required)
Performanc
Better (no boxing) Slower for value types (boxing)
Example:
List<int> list = new List<int>();
list.Add(10); // Type-safe
rrayList arrayList = new ArrayList();
rrayList.Add(10);
int num = (int)arrayList[0]; // Casting required
Best Practice:
lways prefer List<T> in new code. Use ArrayList only when working with legacy
systems.
C# Collections C# Programming Tutorial · Collections
Use a foreach loop, which iterates from top to bottom (LIFO order).
Example:
foreach (var item in stack)
{
Console.WriteLine(item);
}
This does not modify the stack — it's read-only iteration.
📘 C# HashSet<T> – Interview Questions
& Answers
C# Collections C# Programming Tutorial · Collections
Answer: Use the Reverse() method. Example: list.Reverse(); Use case: Reversing order of recent messages or results.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Use a foreach loop with KeyValuePair<TKey, TValue>:
foreach (KeyValuePair<string, int> pair in dictionary)
{
Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
}
Or use deconstruction (C# 7+):
foreach (var (key, value) in dictionary)
{
Console.WriteLine($"{key} = {value}");
}C# Collections C# Programming Tutorial · Collections
You can iterate using:
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Use the Clear() method to remove all elements. Example: list.Clear();
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
rgumentNullException.
This restriction ensures the integrity of hashing, which is used internally by the dictionary.
C# Collections C# Programming Tutorial · Collections
Answer: Method Returns Find() First match FindAll () ll matches in a new list Example: var firstEven = list.Find(x => x % 2 == 0); var allEvens = list.FindAll(x => x % 2 == 0);
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
KeyValuePair<TKey, TValue> represents a single item in a dictionary — a key-value
pair.
Used in:
Example:
foreach (KeyValuePair<string, int> entry in dictionary)
{
Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");
}C# Collections C# Programming Tutorial · Collections
Answer: Use the Clear() method to remove all key-value pairs. dictionary.Clear(); This resets the dictionary to an empty state. 📘 C# Queue<T> – Interview Questions &
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use the Clear() method to remove all key-value pairs. dictionary.Clear(); This resets the dictionary to an empty state. 📘 C# Queue<T> – Interview Questions &
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Contains(item) checks whether the item exists in the list. It uses Equals() internally. Example: bool exists = list.Contains(10); Note: For custom objects, override Equals() and GetHashCode().
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Capacity is the number of elements the list can hold before resizing. It is greater than or equal to Count. Example: list.Capacity = 100; // Optional performance tuning
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Property Meaning Count Number of elements currently in the list Capacit Total allocated slots (memory reserved) Example: Console.WriteLine($"Count: {list.Count}, Capacity: {list.Capacity}");
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use GroupBy, Distinct, or nested loops. Example: bool hasDuplicates = list.Count != list.Distinct().Count();
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use ToArray() method. Example: int[] array = list.ToArray(); Useful when interfacing with APIs that require arrays.
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: list = list.Distinct().ToList(); For custom objects, override Equals() and GetHashCode().
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
C# Collections C# Programming Tutorial · Collections
Answer: Use IndexOf(item) or FindIndex(predicate). Example: int index = list.IndexOf(10); int indexByCondition = list.FindIndex(x => x > 100); 📘 C# Dictionary<TKey, TValue> – Interview Questions & Answers
In a production C# Collections application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.