Technical interview questions with detailed answers—organized by course, like Dot Net Tutorials interview sections. Original content for Toolliyo Academy.
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
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>();
ages.Add("Alice", 30);
ages.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.
Follow:
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}
Follow:
C# Collections C# Programming Tutorial · Collections
List<string> fruits = new List<string> { "Apple", "Banana" };
foreach (var fruit in fruits)
Console.WriteLine(fruit);
C# Collections C# Programming Tutorial · Collections
accurately.
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
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
ArrayList 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
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)
Follow:
// Custom validation
if (item == null) throw new
ArgumentNullException(nameof(item));
base.InsertItem(index, item);
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
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
Generic collections offer several advantages:
Follow:
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
Follow:
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 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.
Follow:
C# Collections C# Programming Tutorial · Collections
numbers.AddFirst(5); // Adds 5 at the beginning
numbers.AddLast(30); // Adds 30 at the end
C# Collections C# Programming Tutorial · Collections
Feature HashSet<T> List<T> Dictionary<TKey,
TValue>
Allows
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
Follow:
cache-friendly.
Previous), leading to more memory overhead.
performance than LinkedList<T>, especially for large collections.
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
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
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
clear, allowing easy customization.
extensibility.
validation, event firing).
C# Collections C# Programming Tutorial · Collections
Use the Add() method or the indexer []:
// Using Add()
dictionary.Add("key1", "value1");
// Using indexer
dictionary["key2"] = "value2";
Follow:
Note: Add() throws an exception if the key already exists, while indexer will overwrite the
value.
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:
Follow:
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
for (int i = 0; i < fruits.Count; i++)
Console.WriteLine(fruits[i]);
C# Collections C# Programming Tutorial · Collections
You can use the Add() or AddRange() method.
Example:
Follow:
List<int> numbers = new List<int>();
numbers.Add(10); // Add single item
numbers.AddRange(new int[] { 20, 30 }); // Add multiple
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
Follow:
C# Collections C# Programming Tutorial · Collections
Follow:
C# Collections C# Programming Tutorial · Collections
Operation Method Description
Add Enqueue
Adds 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(); // Remove
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);
Follow:
C# Collections C# Programming Tutorial · Collections
Follow:
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 top
C# Collections C# Programming Tutorial · Collections
ConcurrentQueue, BlockingCollection, etc.).
ReaderWriterLock around critical sections when using non-thread-safe
collections.
C# Collections C# Programming Tutorial · Collections
Review the concept and prepare a concise verbal explanation with a real project example.
C# Collections C# Programming Tutorial · Collections
Scenario Best Choice Trade-offs
Fast indexed
access
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
Add:
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
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
Use the Remove(key) method:
dictionary.Remove("key1");
Returns true if the key was found and removed, false otherwise.
C# Collections C# Programming Tutorial · Collections
All these operations generally have O(1) average time complexity due to the underlying
hash table structure.
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.
Follow:
C# Collections C# Programming Tutorial · Collections
(used in sorting operations like Sort()).
GetHashCode(T obj) to determine equality and hashing (used in dictionaries,
Follow:
sets, etc.).
beyond default implementations.
C# Collections C# Programming Tutorial · Collections
Searching by key uses binary search, so the time complexity is O(log n).
Follow:
C# Collections C# Programming Tutorial · Collections
These operations are fast and efficient due to the internal array structure.
C# Collections C# Programming Tutorial · Collections
Add all elements from the collection to a HashSet<T>, which automatically removes
duplicates.
Follow:
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
Use a foreach loop to traverse the linked list from start to end.
foreach (var num in numbers)
Console.WriteLine(num);
C# Collections C# Programming Tutorial · Collections
Follow:
Due to the internal circular array and pointer arithmetic, both operations are highly efficient
unless resizing is needed (which is O(n), but infrequent).
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
expressive.
performance.
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
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
Additional
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.
Follow:
📘 C# Collections: Performance &
Memory Considerations – Interview Q&A
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
Accessing an element by index is O(1) (constant time) — same as arrays.
Example:
int first = numbers[0]; // O(1)
Follow:
C# Collections C# Programming Tutorial · Collections
Example:
dictionary.ContainsKey("Alice"); // true/false
dictionary.ContainsValue(30); // true/false
C# Collections C# Programming Tutorial · Collections
Follow:
List<T>(capacity)) to avoid frequent resizing.
LinkedList<T> if indexing is needed).
non-generic.
📘 C# Advanced Collection Topics –
Interview Questions & Answers
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
reference): O(1)
C# Collections C# Programming Tutorial · Collections
Follow:
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
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
already exists
C# Collections C# Programming Tutorial · Collections
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).
Follow:
C# Collections C# Programming Tutorial · Collections
IList<T> extends ICollection<T> and allows:
Follow:
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:
bool hasItem = numbers.Contains(10);
int index = numbers.IndexOf(10);
var result = numbers.Find(x => x > 50);
C# Collections C# Programming Tutorial · Collections
Use the Peek() method.
Example:
int top = stack.Peek();
Follow:
This is useful when you just want to inspect the top element without altering the stack.
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);
Follow:
📘 C# Thread-Safe Collections –
Interview Questions & Answers
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
Useful when you want to see what’s next without modifying the queue.
C# Collections C# Programming Tutorial · Collections
Use a foreach loop which iterates over the elements in sorted ascending order:
foreach (var item in sortedSet)
Console.WriteLine(item);
Follow:
C# Collections C# Programming Tutorial · Collections
Due to the underlying balanced tree structure, these operations have O(log n) time
complexity.
📘 C# Collection Initializers & LINQ –
Interview Questions & Answers
C# Collections C# Programming Tutorial · Collections
Operation LinkedList<T> List<T>
Indexed access O(n) (no indexing) O(1) (direct access)
Add/Remove at
start/end
O(1) O(n) (start), O(1) (end)
Add/Remove in middle O(1) (with node ref) O(n) (shifts elements)
Follow:
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 & Answers
C# Collections C# Programming Tutorial · Collections
Union: Combines all unique elements from both sets
set1.UnionWith(set2);
Intersection: Keeps only elements present in both sets
set1.IntersectWith(set2);
Example:
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}
Follow:
set1.IntersectWith(set2); // set1 = {3, 4, 5}
C# 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.
Follow:
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");
Follow:
// 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.
Follow:
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
Method Purpose
Add() Adds one item
AddRange
Adds multiple items (collection)
Example:
list.Add(1); // One item
Follow:
list.AddRange(new[] { 2, 3, 4 }); // Multiple
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
Use the Clear() method to remove all elements.
Example:
tasks.Clear();
After calling Clear(), the queue is empty (Count == 0).
Follow:
C# Collections C# Programming Tutorial · Collections
Method Purpose Return Value
Add(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
C# Collections C# Programming Tutorial · Collections
Example:
list.Insert(0, 99); // Add at beginning
list.Add(100); // Add at end
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
ArrayList arr = new ArrayList();
arr.Add(1);
arr.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.
Follow:
C# Collections C# Programming Tutorial · Collections
Use the Count property.
if (stack.Count == 0)
Console.WriteLine("Stack is empty");
Unlike some languages, C# stacks do not provide an IsEmpty property.
Follow:
C# Collections C# Programming Tutorial · Collections
Example:
foreach (var key in dictionary.Keys)
Console.WriteLine(key);
foreach (var value in dictionary.Values)
Follow:
Console.WriteLine(value);
C# Collections C# Programming Tutorial · Collections
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();
C# Collections C# Programming Tutorial · Collections
Again, use the Peek() method:
var front = queue.Peek();
Difference from Dequeue():
📘 C# Stack<T> – Interview Questions &
Follow:
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
Example:
dictionary.Add("John", 25);
dictionary.Add("John", 30); // Exception
dictionary["John"] = 30; // Overwrites the value safely
C# Collections C# Programming Tutorial · Collections
Use a foreach loop; the iteration order is not guaranteed.
foreach (var item in uniqueNumbers)
Console.WriteLine(item);
📘 C# LinkedList<T> – Interview
Questions & Answers
C# Collections C# Programming Tutorial · Collections
Use the Sort() method or provide a custom comparer.
Example:
list.Sort(); // Default sort (ascending)
list.Sort((a, b) => b.CompareTo(a)); // Descending
C# Collections C# Programming Tutorial · Collections
Use the Clear() method to remove all elements.
stack.Clear();
After this, Count becomes 0, and the internal array is reset.
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)
Follow:
Example:
List<int> list = new List<int>();
list.Add(10); // Type-safe
ArrayList arrayList = new ArrayList();
arrayList.Add(10);
int num = (int)arrayList[0]; // Casting required
Best Practice:
Always prefer List<T> in new code. Use ArrayList only when working with legacy
systems.
C# Collections C# Programming Tutorial · Collections
Use the Reverse() method.
Example:
list.Reverse();
Follow:
Use case: Reversing order of recent messages or results.
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}");
Follow:
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
Use the Clear() method to remove all elements.
Example:
list.Clear();
C# Collections C# Programming Tutorial · Collections
ArgumentNullException.
This restriction ensures the integrity of hashing, which is used internally by the dictionary.
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
Method Returns
Find() First match
FindAll
All matches in a new list
Example:
var firstEven = list.Find(x => x % 2 == 0);
var allEvens = list.FindAll(x => x % 2 == 0);
C# Collections C# Programming Tutorial · Collections
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 &
C# Collections C# Programming Tutorial · Collections
Contains(item) checks whether the item exists in the list. It uses Equals() internally.
Example:
Follow:
bool exists = list.Contains(10);
Note: For custom objects, override Equals() and GetHashCode().
C# Collections C# Programming Tutorial · Collections
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
C# Collections C# Programming Tutorial · Collections
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}");
C# Collections C# Programming Tutorial · Collections
Use GroupBy, Distinct, or nested loops.
Follow:
Example:
bool hasDuplicates = list.Count != list.Distinct().Count();
C# Collections C# Programming Tutorial · Collections
Use ToArray() method.
Example:
int[] array = list.ToArray();
Useful when interfacing with APIs that require arrays.
C# Collections C# Programming Tutorial · Collections
list = list.Distinct().ToList();
For custom objects, override Equals() and GetHashCode().
C# Collections C# Programming Tutorial · Collections
Use IndexOf(item) or FindIndex(predicate).
Example:
int index = list.IndexOf(10);
int indexByCondition = list.FindIndex(x => x > 100);
Follow:
📘 C# Dictionary<TKey, TValue> –
Interview Questions & Answers