Interview Q&A

Technical interview questions with detailed answers—organized by course, like Dot Net Tutorials interview sections. Original content for Toolliyo Academy.

Popular tracks

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:

  • You need a resizable array-like structure
  • You want to perform frequent insertions, deletions, and searches

Example:

List<string> names = new List<string>();

names.Add("Alice");

Permalink

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.

  • Keys must be unique
  • Keys must be non-null (for reference types)
  • Values can be null if the type allows it

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.

Permalink

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.

  • The first item added is the first to be removed.
  • It is part of the System.Collections.Generic namespace.

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");

Permalink

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.

  • The last element added is the first one removed
  • Belongs to System.Collections.Generic

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

Permalink

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);

Permalink

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.

  • Allows efficient insertions and deletions anywhere in the list.
  • Does not support indexed access like List<T>.

Example:

LinkedList<int> numbers = new LinkedList<int>();

numbers.AddLast(10);

numbers.AddLast(20);

Permalink

C# Collections C# Programming Tutorial · Collections

SortedList<TKey, TValue> is a collection of key-value pairs that maintains the

elements sorted by keys.

  • Implements both IDictionary<TKey, TValue> and

IList<KeyValuePair<TKey, TValue>>.

  • Keys are automatically sorted in ascending order based on their natural comparer

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.

Permalink

C# Collections C# Programming Tutorial · Collections

SortedSet<T> is a collection that stores unique elements in sorted order.

  • Implements a self-balancing binary search tree (usually a Red-Black Tree).
  • Automatically maintains elements in ascending sorted order.
  • Provides set operations like union, intersection, and difference.

Example:

SortedSet<int> sortedSet = new SortedSet<int> { 5, 1, 3 };

sortedSet.Add(2); // Sorted order maintained: {1, 2, 3, 5}

Follow:

Permalink

C# Collections C# Programming Tutorial · Collections

List<string> fruits = new List<string> { "Apple", "Banana" };

foreach (var fruit in fruits)

Console.WriteLine(fruit);

Permalink

C# Collections C# Programming Tutorial · Collections

  • Use the Stopwatch class from System.Diagnostics to time operations

accurately.

  • Profile your code using tools like Visual Studio Profiler, dotTrace, or PerfView for

deeper insights.

  • Measure specific operations like add, remove, search, or iteration by running them

multiple times and averaging results.

Example:

var stopwatch = Stopwatch.StartNew();

list.Add(1000);

stopwatch.Stop();

Console.WriteLine($"Add operation took {stopwatch.ElapsedTicks}

ticks");

Permalink

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.

Permalink

C# Collections C# Programming Tutorial · Collections

To implement a custom collection:

  • Derive from existing base classes like Collection<T>, List<T>, or implement

interfaces such as ICollection<T>, IEnumerable<T>, or IList<T>.

  • Override or implement necessary methods like Add(), Remove(),

GetEnumerator(), and indexers.

  • Provide custom behavior, validation, or constraints as needed.

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);

Permalink

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.

Permalink

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).

  • Supports atomic operations like adding, updating, and removing items.
  • Useful in multi-threaded scenarios where data integrity and performance are critical.

Example:

ConcurrentDictionary<int, string> concurrentDict = new

ConcurrentDictionary<int, string>();

concurrentDict.TryAdd(1, "One");

concurrentDict.TryUpdate(1, "Uno", "One");

Permalink

C# Collections C# Programming Tutorial · Collections

Generic collections offer several advantages:

  • Type Safety: Compile-time checking prevents runtime errors.
  • Performance: Avoids boxing/unboxing of value types.
  • Code Clarity: Cleaner code without explicit casting.

Follow:

  • Reusability: Generic code can work with any data type.

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.

Permalink

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)

Permalink

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:

Permalink

C# Collections C# Programming Tutorial · Collections

  • 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

Permalink

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)

Permalink

C# Collections C# Programming Tutorial · Collections

Follow:

  • List<T> uses a contiguous array internally, so memory is compact and

cache-friendly.

  • LinkedList<T> stores elements in nodes with extra pointers (Next and

Previous), leading to more memory overhead.

  • Therefore, List<T> generally has lower memory usage and better cache

performance than LinkedList<T>, especially for large collections.

Permalink

C# Collections C# Programming Tutorial · Collections

Internally, Stack<T> uses an array-based dynamic storage system:

  • When capacity is exceeded, the internal array resizes automatically (typically

doubles)

  • The top of the stack is managed with a private index pointer

This structure provides fast push and pop operations (constant time on average).

Permalink

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

Permalink

C# Collections C# Programming Tutorial · Collections

Internally, Queue<T> uses a circular array to efficiently manage memory and operations.

  • Head pointer marks the front (next item to be dequeued).
  • Tail pointer marks where the next item will be enqueued.
  • Automatically resizes when capacity is exceeded.

This implementation ensures constant time operations for enqueue and dequeue.

Permalink

C# Collections C# Programming Tutorial · Collections

  • Collection<T> is a base class for creating custom collections.
  • It wraps an IList<T> internally and provides virtual methods for insert, remove, and

clear, allowing easy customization.

  • Unlike List<T>, which is optimized for performance, Collection<T> focuses on

extensibility.

  • Useful when you want to create a collection with customized behaviors (e.g.,

validation, event firing).

Permalink

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.

Permalink

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();

Permalink

C# Collections C# Programming Tutorial · Collections

for (int i = 0; i < fruits.Count; i++)

Console.WriteLine(fruits[i]);

Permalink

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

Permalink

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:

Permalink

C# Collections C# Programming Tutorial · Collections

  • When you need a collection of unique elements in sorted order.
  • Performing range queries or retrieving elements in sorted order.
  • Implementing mathematical set operations efficiently.
  • Examples:
  • Leaderboards
  • Scheduling tasks sorted by priority
  • Auto-complete suggestions sorted alphabetically

Follow:

Permalink

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

Permalink

C# Collections C# Programming Tutorial · Collections

  • Filter: Use Where() to select elements based on a condition.
  • Sort: Use OrderBy() or OrderByDescending().
  • Group: Use GroupBy() to group elements by a key.

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:

Permalink

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

Permalink

C# Collections C# Programming Tutorial · Collections

  • Use thread-safe collections provided by .NET (ConcurrentDictionary,

ConcurrentQueue, BlockingCollection, etc.).

  • Use synchronization primitives like lock, Mutex, Semaphore, or

ReaderWriterLock around critical sections when using non-thread-safe

collections.

  • Avoid shared mutable state or design the program to minimize contention.
  • Use immutable collections when possible to eliminate synchronization.
Permalink

C# Collections C# Programming Tutorial · Collections

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

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

Permalink

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

Permalink

C# Collections C# Programming Tutorial · Collections

Use methods like:

  • Remove(item) – removes first occurrence
  • RemoveAt(index) – removes by index
  • RemoveAll(predicate) – removes all matching a condition
  • Clear() – removes all items

Example:

numbers.Remove(10);

numbers.RemoveAt(0);

numbers.RemoveAll(x => x > 100);

numbers.Clear();

Permalink

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.

Permalink

C# Collections C# Programming Tutorial · Collections

All these operations generally have O(1) average time complexity due to the underlying

hash table structure.

Permalink

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:

Permalink

C# Collections C# Programming Tutorial · Collections

  • IComparer<T> defines a method Compare(T x, T y) for custom sorting logic

(used in sorting operations like Sort()).

  • IEqualityComparer<T> defines methods Equals(T x, T y) and

GetHashCode(T obj) to determine equality and hashing (used in dictionaries,

Follow:

sets, etc.).

  • They allow collections to customize how items are compared or checked for equality,

beyond default implementations.

Permalink

C# Collections C# Programming Tutorial · Collections

Searching by key uses binary search, so the time complexity is O(log n).

Follow:

Permalink

C# Collections C# Programming Tutorial · Collections

  • 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.

Permalink

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}.

Permalink

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);

Permalink

C# Collections C# Programming Tutorial · Collections

Follow:

  • 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).

Permalink

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)

Permalink

C# Collections C# Programming Tutorial · Collections

  • Concise and readable code: LINQ makes querying collections clear and

expressive.

  • Declarative style: You focus on what to retrieve, not how.
  • Powerful operations: Filtering, sorting, grouping, joining, projecting, and more.
  • Deferred execution: Queries execute only when results are needed, improving

performance.

  • Strongly typed: Compile-time checking and IntelliSense support.
Permalink

C# Collections C# Programming Tutorial · Collections

  • Deep cloning copies the collection and all objects inside it recursively.
  • Ways to deep clone:
  • Implement ICloneable in your objects with deep clone logic.
  • Use serialization (binary, XML, JSON) to serialize and deserialize objects.
  • Manually create new instances of each item.

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.

Permalink

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

Permalink

C# Collections C# Programming Tutorial · Collections

ICollection<T> extends IEnumerable<T> and adds features like:

  • Counting (Count property)
  • Adding and removing items (Add, Remove)
  • Checking for existence (Contains)

Difference:

  • IEnumerable<T> is read-only and forward-only iteration.
  • ICollection<T> adds modification capabilities.

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.

Permalink

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:

Permalink

C# Collections C# Programming Tutorial · Collections

  • ContainsKey(key) – checks for key existence
  • ContainsValue(value) – checks for value

Example:

dictionary.ContainsKey("Alice"); // true/false

dictionary.ContainsValue(30); // true/false

Permalink

C# Collections C# Programming Tutorial · Collections

Follow:

  • Pre-allocate capacity when you know the expected size (e.g., new

List<T>(capacity)) to avoid frequent resizing.

  • Use value types or structs when appropriate to reduce reference overhead.
  • Choose collections with lower overhead for your use case (e.g., List<T> instead of

LinkedList<T> if indexing is needed).

  • Use immutable collections or pooling to minimize allocations.
  • Avoid unnecessary boxing/unboxing by using generic collections instead of

non-generic.

  • Regularly trim collections if supported (e.g., List<T>.TrimExcess()).

📘 C# Advanced Collection Topics –

Interview Questions & Answers

Permalink

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

Permalink

C# Collections C# Programming Tutorial · Collections

  • 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
Permalink

C# Collections C# Programming Tutorial · Collections

  • Define your custom object class.

Follow:

  • Create a collection class that holds objects of that type using generics or directly.

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.

Permalink

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

Permalink

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:

Permalink

C# Collections C# Programming Tutorial · Collections

IList<T> extends ICollection<T> and allows:

  • Indexed access (like arrays)

Follow:

  • Inserting and removing at specific positions

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.

Permalink

C# Collections C# Programming Tutorial · Collections

  • Contains(item)
  • IndexOf(item)
  • Find(predicate)
  • FindAll(predicate)
  • Exists(predicate)
  • BinarySearch(item) (for sorted lists)

Example:

bool hasItem = numbers.Contains(10);

int index = numbers.IndexOf(10);

var result = numbers.Find(x => x > 50);

Permalink

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.

Permalink

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

Permalink

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.

Permalink

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:

Permalink

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

Permalink

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

Permalink

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}

Permalink

C# Collections C# Programming Tutorial · Collections

These interfaces provide read-only access to collections:

  • IReadOnlyCollection<T> provides Count and enumeration.
  • IReadOnlyList<T> provides index-based access without modification.

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:

Permalink

C# Collections C# Programming Tutorial · Collections

  • Actually, SortedList<TKey, TValue> stores key-value pairs sorted by keys.
  • To store items in a specific order, use the key to represent the sorting criteria.
  • Keys must be unique and implement IComparable or provide a custom

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:

Permalink

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

Permalink

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

Permalink

C# Collections C# Programming Tutorial · Collections

Peek() returns the top element without removing it. It’s helpful for:

  • Conditional checks
  • Previewing what's next
  • Preventing accidental removal

Example:

if (stack.Count > 0)

var current = stack.Peek();

Throws InvalidOperationException if the stack is empty.

Permalink

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:

Permalink

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

Permalink

C# Collections C# Programming Tutorial · Collections

  • 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

Permalink

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:

Permalink

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:

Permalink

C# Collections C# Programming Tutorial · Collections

  • dictionary.Keys – returns a collection of all keys
  • dictionary.Values – returns a collection of all values

Example:

foreach (var key in dictionary.Keys)

Console.WriteLine(key);

foreach (var value in dictionary.Values)

Follow:

Console.WriteLine(value);

Permalink

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();

Permalink

C# Collections C# Programming Tutorial · Collections

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 &

Follow:

Permalink

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.

Permalink

C# Collections C# Programming Tutorial · Collections

  • Using Add() will throw a System.ArgumentException
  • Using the indexer (dictionary[key] = value) will overwrite the existing value

Example:

dictionary.Add("John", 25);

dictionary.Add("John", 30); // Exception

dictionary["John"] = 30; // Overwrites the value safely

Permalink

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

Permalink

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

Permalink

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.

Permalink

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.

Permalink

C# Collections C# Programming Tutorial · Collections

Use the Reverse() method.

Example:

list.Reverse();

Follow:

Use case: Reversing order of recent messages or results.

Permalink

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:

Permalink

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

Permalink

C# Collections C# Programming Tutorial · Collections

Use the Clear() method to remove all elements.

Example:

list.Clear();

Permalink

C# Collections C# Programming Tutorial · Collections

  • For reference types, null keys are not allowed — adding one throws an

ArgumentNullException.

  • For value types, keys must be non-nullable (like int, Guid).

This restriction ensures the integrity of hashing, which is used internally by the dictionary.

Permalink

C# Collections C# Programming Tutorial · Collections

You can iterate using:

Permalink

C# Collections C# Programming Tutorial · Collections

KeyValuePair<TKey, TValue> represents a single item in a dictionary — a key-value

pair.

Used in:

  • Iteration
  • LINQ queries
  • Return values from dictionary enumerators

Example:

foreach (KeyValuePair<string, int> entry in dictionary)

Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}");

Permalink

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);

Permalink

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 &

Permalink

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().

Permalink

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

Permalink

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}");

Permalink

C# Collections C# Programming Tutorial · Collections

Use GroupBy, Distinct, or nested loops.

Follow:

Example:

bool hasDuplicates = list.Count != list.Distinct().Count();

Permalink

C# Collections C# Programming Tutorial · Collections

Use ToArray() method.

Example:

int[] array = list.ToArray();

Useful when interfacing with APIs that require arrays.

Permalink

C# Collections C# Programming Tutorial · Collections

list = list.Distinct().ToList();

For custom objects, override Equals() and GetHashCode().

Permalink

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

Permalink