Why use indexers?

This is a discussion on Why use indexers? within the C# Programming forums, part of the General Programming Boards category; Hi!
Can someone enlighten me as to when, where, and why one would use a class indexer? I am trying ...

Why use indexers?

Hi!

Can someone enlighten me as to when, where, and why one would use a class indexer? I am trying to come up with an example which features the benefits of indexers--and am coming up dry. Is there more to it than saving a method declaration? So, please share with me what they are actually used for and what the benefit is.

Defining an indexer allows you to create classes that act like "virtual arrays." Instances of that class can be accessed using the [] array access operator. Defining an indexer in C# is similar to defining operator [] in C++, but is considerably more flexible. For classes that encapsulate array- or collection-like functionality, using an indexer allows the users of that class to use the array syntax to access the class.

If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

You can't always use the built-in arrays to do what you need to do. For instance, it can be useful to have collections that notify you via events when items are added, removed, or changed. It can be useful to use strings, floats, or user-defined classes as the key to retrieve members from your collection. Allowing users to create indexers lets users keep a familiar syntax for member access, increasing the readability of the code.

As for benefits, I can't say for certain, but I can suggest. The same argument you're making against indexers could apply against all properties in general. Why use properties when you could just create methods to do the same thing? Since properties are often inlined by the compiler for efficiency, an indexer might be a way of allowing safe and optimized access to collection members. Using methods for this would likely be slower due to the overhead of a function call.

If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein