What is the output of this C# code?
public class Person { public string Name { get; set; } public Person(string name) { Name = name; } } public class Group { private Person[] people = { new Person("Alice"), new Person("Bob"), new Person("Charlie") }; public Person this[int index] { get { return people[index]; } set { people[index] = value; } } } var group = new Group(); Console.WriteLine(group[1].Name);
Remember that arrays are zero-based indexed.
The indexer returns the Person object at the given index. Index 1 corresponds to the second element, which is "Bob".
What will be printed after running this code?
public class Item { public int Value { get; set; } public Item(int value) { Value = value; } } public class Container { private Item[] items = { new Item(10), new Item(20), new Item(30) }; public Item this[int index] { get => items[index]; set => items[index] = value; } } var container = new Container(); container[1] = new Item(99); Console.WriteLine(container[1].Value);
Check what happens when you assign a new Item to the indexer.
The set accessor replaces the Item at index 1 with a new Item whose Value is 99. So printing container[1].Value outputs 99.
What error will this code produce when compiled?
public class Box { private int[] data = new int[3]; public int this[int index] { get { return data[index]; } set { data[index] = value; } } }
Look carefully at how the array is accessed in the set accessor.
In C#, arrays are indexed with square brackets [], not parentheses (). Using parentheses causes a syntax error.
What is the output of this code?
public struct Point { public int X, Y; public Point(int x, int y) { X = x; Y = y; } public override string ToString() => $"({X},{Y})"; } public class Polygon { private Point[] points = { new Point(1,2), new Point(3,4), new Point(5,6) }; public Point this[int index] { get => points[index]; set => points[index] = value; } } var poly = new Polygon(); poly[2] = new Point(7,8); Console.WriteLine(poly[2]);
Remember structs are value types and can be replaced via indexer.
The indexer set replaces the point at index 2 with (7,8). Printing poly[2] calls ToString() and outputs "(7,8)".
Which of the following is the best reason to implement an indexer with a custom type in C#?
Think about what indexers provide in terms of syntax and usage.
Indexers let you access objects like arrays, improving code readability and hiding internal data structures. They do not enforce immutability, serialization, or replace constructors.