C#.NET indexers — What kinds of types can declare an indexer and thus be indexed like an array?

Difficulty: Easy

Correct Answer: 1) A class 3) A struct 5) An interface

Explanation:


Introduction / Context:
Indexers provide array-like access to instances. They are declared with the this keyword and one or more parameters. This question asks which categories in C# are eligible to define indexers.



Given Data / Assumptions:

  • C# supports indexers on classes, structs, and interfaces.
  • Properties and functions themselves are not entities that “hold” indexers; they are members.


Concept / Approach:
An indexer is a member of a type. The C# language allows an indexer declaration inside a class or a struct, and an indexer signature can also be declared in an interface (with accessors but without bodies). Properties and methods are not containers of indexers; rather, indexers are peers to them.



Step-by-Step Solution:

Confirm eligibility: class → yes; struct → yes; interface → yes.Eliminate property/function: these are members, not types that declare indexers.Select (1, 3, 5) as the correct grouping.


Verification / Alternative check:
Write minimal declarations in each construct. For interfaces, use signatures like int this[int i] { get; set; } with no bodies.



Why Other Options Are Wrong:

  • B/D: Include “function” or “property,” which cannot contain indexers.
  • C: Omits class even though it is valid.


Common Pitfalls:
Confusing an indexer with a property that returns an array; the latter is different and does not change indexing rules for the object itself.



Final Answer:
1, 3, 5

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion