Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Indexer declaration in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Indexer declaration
Start
↓
Declare class with indexer
↓
Indexer get/set called with index
↓
Access or modify internal data
↓
Return or update value
↓
End
This flow shows how a class with an indexer lets you use array-like access to get or set values inside the class.
Execution Sample
C Sharp (C#)
class Sample {
  private int[] data = {10, 20, 30};
  public int this[int i] {
    get => data[i];
    set => data[i] = value;
  }
}

var s = new Sample();
Console.WriteLine(s[1]);
s[1] = 50;
Console.WriteLine(s[1]);
This code defines a class with an indexer to get and set values in an internal array using square brackets.
Execution Table
StepActionIndexValue BeforeValue AfterOutput
1Create Sample instance----
2Read s[1]1202020
3Set s[1] = 5012050-
4Read s[1]1505050
5End----
💡 Finished accessing and modifying values using the indexer.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
data[0]1010101010
data[1]2020505050
data[2]3030303030
Key Moments - 2 Insights
Why can we use square brackets on the object s like s[1]?
Because the class Sample declares an indexer with 'this[int i]', it allows using square brackets to get or set values inside the object, as shown in steps 2 and 3 of the execution_table.
What happens if we try to access an index outside the array range?
An exception will occur because the indexer accesses the internal array directly without bounds checking. This is not shown in the current execution_table but is important to remember.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output when reading s[1] at step 2?
A20
B50
C10
DError
💡 Hint
Check the Output column at step 2 in the execution_table.
At which step does the value at index 1 change in the data array?
AStep 2
BStep 4
CStep 3
DStep 1
💡 Hint
Look at the Value After column for data[1] in variable_tracker after each step.
If we remove the set accessor from the indexer, what would happen when executing step 3?
AIt would update the value successfully.
BIt would cause a compile-time error.
CIt would throw a runtime exception.
DIt would ignore the assignment silently.
💡 Hint
Remember that without a set accessor, the indexer is read-only and cannot assign values.
Concept Snapshot
Indexer declaration syntax:
public returnType this[type index] {
  get { ... }
  set { ... }
}

Allows objects to be accessed like arrays.
Get returns value at index.
Set updates value at index.
Useful for internal collections.
Full Transcript
This example shows how to declare and use an indexer in C#. The class Sample has a private array and an indexer that lets you get or set values using square brackets. When you create an instance and use s[1], it calls the get accessor returning the value at index 1. When you assign s[1] = 50, it calls the set accessor updating the value. The execution table traces these steps and shows how the internal array changes. Beginners often wonder why square brackets work on objects; it's because of the indexer declaration. Also, if you remove the set accessor, you cannot assign values, causing a compile error.

Practice

(1/5)
1. What is the purpose of an indexer in a C# class?
easy
A. To declare a constant value inside the class
B. To allow objects to be accessed like arrays using square brackets
C. To create a new class instance
D. To define a method that returns the class name

Solution

  1. Step 1: Understand what an indexer does

    An indexer lets you access elements in an object using square brackets, similar to arrays.
  2. Step 2: Compare options with this definition

    Only To allow objects to be accessed like arrays using square brackets describes this behavior correctly.
  3. Final Answer:

    To allow objects to be accessed like arrays using square brackets -> Option B
  4. Quick Check:

    Indexer = access with [] [OK]
Hint: Indexers let objects act like arrays with [] access [OK]
Common Mistakes:
  • Confusing indexers with methods
  • Thinking indexers create new objects
  • Mixing indexers with constants
2. Which of the following is the correct syntax to declare an indexer in C#?
easy
A. public int this[int index] get set;
B. public int indexer(int index) { get; set; }
C. public int this[index] { get; set; }
D. public int this[int index] { get; set; }

Solution

  1. Step 1: Recall indexer syntax

    An indexer uses the keyword this with a parameter list in square brackets and defines get and/or set accessors inside braces.
  2. Step 2: Check each option

    public int this[int index] { get; set; } matches the correct syntax exactly. public int indexer(int index) { get; set; } uses a method-like name, which is incorrect. public int this[index] { get; set; } misses the type in the parameter. public int this[int index] get set; misses braces and semicolons.
  3. Final Answer:

    public int this[int index] { get; set; } -> Option D
  4. Quick Check:

    Indexer syntax = this[type param] { get; set; } [OK]
Hint: Indexer syntax always uses 'this' with parameter in brackets [OK]
Common Mistakes:
  • Using method name instead of 'this'
  • Omitting parameter type
  • Missing braces around get/set
3. What will be the output of the following code?
class Sample {
  private int[] data = {10, 20, 30};
  public int this[int i] {
    get { return data[i]; }
    set { data[i] = value; }
  }
}

var s = new Sample();
s[1] = 50;
Console.WriteLine(s[1]);
medium
A. 50
B. 20
C. 30
D. Compilation error

Solution

  1. Step 1: Understand the indexer behavior

    The indexer accesses the private array data. Setting s[1] = 50; changes data[1] from 20 to 50.
  2. Step 2: Check the output of Console.WriteLine(s[1])

    This prints the updated value at index 1, which is 50.
  3. Final Answer:

    50 -> Option A
  4. Quick Check:

    Indexer set changes value, output = 50 [OK]
Hint: Indexer set changes array value, get returns updated value [OK]
Common Mistakes:
  • Assuming original value prints
  • Confusing indexer with method call
  • Expecting compilation error
4. Identify the error in this indexer declaration:
public string this[int index]
{
  get { return data[index]; }
  set data[index] = value;
}
medium
A. Parameter name cannot be 'index'
B. Indexer must return int, not string
C. Missing braces around set accessor body
D. Missing semicolon after get accessor

Solution

  1. Step 1: Review accessor syntax

    Both get and set accessors must have braces enclosing their bodies.
  2. Step 2: Locate the error

    The set accessor lacks braces around data[index] = value;, causing a syntax error.
  3. Final Answer:

    Missing braces around set accessor body -> Option C
  4. Quick Check:

    Accessor bodies need braces { } [OK]
Hint: Always use braces { } for get and set bodies [OK]
Common Mistakes:
  • Omitting braces in set accessor
  • Wrong return type assumption
  • Thinking parameter name is restricted
5. You want to create a class that stores names and allows access by index using an indexer. Which of the following indexer declarations correctly supports both reading and writing names by index?
hard
A. public string this[int i] { get { return names[i]; } set { names[i] = value; } }
B. public string this[int i] { set { names[i] = value; } }
C. public string this[int i] { get { return names[i]; } }
D. public string this[string name] { get { return name; } set { name = value; } }

Solution

  1. Step 1: Understand requirements for read/write access

    The indexer must have both get and set accessors to allow reading and writing by index.
  2. Step 2: Evaluate each option

    public string this[int i] { get { return names[i]; } } only has get, so no writing. public string this[int i] { set { names[i] = value; } } only has set, so no reading. public string this[int i] { get { return names[i]; } set { names[i] = value; } } has both get and set with int index parameter, which is correct. public string this[string name] { get { return name; } set { name = value; } } uses a string parameter, which does not match the requirement to access by index.
  3. Final Answer:

    public string this[int i] { get { return names[i]; } set { names[i] = value; } } -> Option A
  4. Quick Check:

    Read/write indexer needs both get and set [OK]
Hint: Read/write indexers need both get and set accessors [OK]
Common Mistakes:
  • Defining only get or only set
  • Using wrong parameter type
  • Confusing indexer parameter with property
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard