Warm‑up: Arrays vs List vs Dictionary vs Indexer (with answer)
Warm‑up (with answer): You have a product catalog loaded once at startup and used for fast lookups. Decide when to use: - array T[] - List<T> - Dictionary<TKey,TValue> - C# Indexer You must provide a short explanation + a tiny code snippet that demonstrates an indexer usage.
using System; // Console
using System.Collections.Generic; // Dictionary
namespace ItTechGenie.M1.ArraysIndexers.WarmUp
{
public class Catalog
{
private readonly Dictionary<string, string> _bySku = // fast lookup map
new(StringComparer.OrdinalIgnoreCase);
// ✅ TODO: Student must implement only this indexer
public string this[string sku] // indexer: Catalog["SKU-001"]
{
get
{
// TODO: return product line by sku; if not found return "NOT_FOUND"
throw new NotImplementedException();
}
}
public void Add(string sku, string line) // add entry
{
_bySku[sku] = line; // insert/replace
}
}
internal class Program
{
static void Main()
{
var c = new Catalog(); // create catalog
c.Add("SKU-001", "SKU-001 "Pen Blue" ₹10 ✅"); // add line
c.Add("SKU-α12", "SKU-α12 "Note Book" ₹45 !@#"); // add line
Console.WriteLine(c["SKU-α12"]); // use indexer
}
}
}
Warm‑up Answer (Concept + Code)
Guideline: - Use T[] when size is fixed and you want fastest indexed access (O(1)) and minimal overhead. - Use List<T> when size can grow/shrink; still O(1) index access but resizing cost. - Use Dictionary<TKey,TValue> for key-based lookup (avg O(1) by key). - Use Indexer to provide "array-like" access syntax on your own type, often wrapping Dictionary/array. In this warm-up, Catalog exposes a Dictionary via an indexer so consumers can call c["SKU-α12"].
public string this[string sku]
{
get
{
sku = (sku ?? "").Trim(); // normalize
if (sku.Length == 0) return "NOT_FOUND"; // empty key
return _bySku.TryGetValue(sku, out var line) ? line : "NOT_FOUND"; // lookup
}
}