Consider the following C# class with an indexer. What will be printed when the program runs?
using System; class Sample { private string[] data = {"zero", "one", "two"}; public string this[int index] { get { return data[index]; } set { data[index] = value; } } } class Program { static void Main() { Sample s = new Sample(); s[1] = "ONE"; Console.WriteLine(s[1]); } }
Think about what happens when you assign a new value to s[1].
The indexer allows accessing the data array by index. Assigning s[1] = "ONE" changes the second element. So printing s[1] outputs "ONE".
What error will this C# code produce when compiled?
class Test { private int[] values = new int[3]; public int this[int index] { get { return values[index]; } // Missing set accessor } } class Program { static void Main() { Test t = new Test(); t[0] = 10; } }
Check if the indexer allows setting a value.
The indexer only has a get accessor, so it is read-only. Trying to assign t[0] = 10 causes a compile-time error.
Examine the code below. Why does it throw an exception at runtime?
class Container { private int[] arr = new int[2]; public int this[int index] { get { if (index < 0 || index >= arr.Length) throw new System.IndexOutOfRangeException(); return arr[index]; } set { arr[index] = value; } } } class Program { static void Main() { Container c = new Container(); c[2] = 5; } }
Look at how the set accessor handles the index.
The set accessor assigns arr[index] = value without checking if index is valid. Since arr has length 2, index 2 is out of range, causing a runtime exception.
Which of the following C# indexer declarations is syntactically correct for indexing by a string key?
Remember the syntax for indexers uses square brackets and braces.
Option C correctly uses square brackets for the parameter and braces for get/set accessors. Option C uses wrong parentheses syntax. Option C misses braces around get/set. Option C uses expression body but lacks set accessor.
Given the following C# code, what will be printed?
using System; using System.Collections.Generic; class MultiIndexer { private Dictionary<(int, int), string> data = new(); public string this[int x, int y] { get => data.TryGetValue((x, y), out var val) ? val : "none"; set => data[(x, y)] = value; } } class Program { static void Main() { MultiIndexer mi = new MultiIndexer(); mi[1, 2] = "A"; mi[3, 4] = "B"; Console.WriteLine(mi[1, 2]); Console.WriteLine(mi[2, 3]); } }
Check which keys are set and which are not.
The indexer uses a dictionary keyed by a tuple (x,y). Only (1,2) and (3,4) are set. Accessing (1,2) returns "A". Accessing (2,3) returns "none" because it is not set.