C#

Collections

6 question(s)

When would you use a List<T> vs an array?

Beginner
Use an array for a fixed-size, performance-critical buffer; use List<T> when the count changes, since it grows and offers Add/Remove/Insert.
int[] fixedGrid = new int[9];
var items = new List<string>(); items.Add("a");
Real-world example A game board is an array; a shopping cart is a List<T>.

When should you use a Dictionary<TKey,TValue>?

Beginner
When you need fast key-based lookups (O(1) average). Keys are unique; use TryGetValue to avoid exceptions on missing keys.
var prices = new Dictionary<string,decimal>{["pen"]=1.5m};
if (prices.TryGetValue("pen", out var p)) { }
Real-world example Caching users by Id or counting word frequencies.

What is the difference between IEnumerable, ICollection and IList?

Intermediate
IEnumerable supports iteration only; ICollection adds Count/Add/Remove; IList adds indexed access and Insert. Accept the least specific type your method needs.
void Print(IEnumerable<int> xs) {}
int First(IList<int> xs) => xs[0];
Real-world example Accepting IEnumerable<T> in APIs keeps callers flexible (arrays, lists, LINQ).

What does HashSet<T> provide and when do you use it?

Intermediate
A set of unique elements with fast Contains/Add and set operations. Adding a duplicate is a no-op.
var seen = new HashSet<int>();
if (!seen.Add(id)) Console.WriteLine("duplicate");
Real-world example De-duplicating ids or checking membership in a loop without O(n) scans.

When would you reach for a ConcurrentDictionary or an immutable collection?

Advanced
Use ConcurrentDictionary for thread-safe reads/writes without external locks; use ImmutableList/Dictionary when you want safe sharing across threads via copy-on-write snapshots.
var cache = new ConcurrentDictionary<int,User>();
cache.GetOrAdd(id, Load);
Real-world example A shared in-memory cache updated by many request threads uses ConcurrentDictionary.

How do you avoid multiple enumeration of an IEnumerable?

Advanced
Deferred sequences re-run their query each time you enumerate them; materialise once with ToList()/ToArray() if you iterate more than once or the source is expensive.
var q = Load().Where(x => x.Active);
var list = q.ToList(); // enumerate once
var count = list.Count; foreach (var x in list) {}
Real-world example Enumerating a database-backed IQueryable twice issues two SQL queries — materialise first.