views:

164

answers:

6

I understand indexer enable us to access a collection within a class as though the class itself were an array.

Suppose we are developing a project ,where do we fit the real pratical usage (example may help) of such indexers ?

+4  A: 

You have several examples in the generic collections of the framework itself. Dictionary is a pretty good example:

Dictionary<string, User> Users;

Users["Jorge"].ResetPassword();

That would be much elegant and simple than

Users.GetElementByKey("Jorge").ResetPassword();
Jorge Córdoba
+1  A: 

Well, the obvious application for using indexers are ... (surprise) Collections.

Such as:

  • Lists:

    list[4]
    
  • Hash tables:

    table["foo"]
    table[Color.Black]
    

Remember that indexers aren't restricted to integer arguments.

Joey
+7  A: 

Look to almost any of the collection classes in the framework for an example. If I were to retrieve an item from a hashtable in a language without an indexer, I would use syntax like:

object o = table.getvalue(key);

where an indexer allows somewhat simpler syntax:

object o = table[key];

(purposely ignoring typing/generics issues in the samples above)

Michael Petrotta
+2  A: 

Suppose you are developing Microsoft .NET Framework for other developers to use (which is really a "real-world project"). You need to write a class that acts like an array but supports getting resized dynamically (the List<T> class). Without an indexer, you could write two methods to get and set elements:

public T get(int index) { ... }
public void set(int index, T value) { ... }
// (Java advocates: no offense intended)

Assume a user of your library wants to increment the second element. She'll have to write:

list.set(1, list.get(1) + 1);

With an indexer, the syntax is much simpler, more readable, and easier to understand:

list[1]++;

(similar arguments apply to things like Dictionary<TKey,TValue>...)

Mehrdad Afshari
+1  A: 

If the collection is sorted, then the first and last elements may be useful for getting a minimum or maximum element.

In ASP.Net, there are several objects that use indexers like Application, Session, and Request.

JB King
+3  A: 

indexer enables us to access a collection within a class as though the class itself were an array.

While that is true, you can write a class that does not have a permanent collection of items within itself, but still be capable to dynamically provide you with a calculated value when indexed. The data may be collected in real-time from the Internet, or any other data source - I imagine, as an example a class SearchResults, that I could use to obtain Google search results for a string like this: Console.out.WriteLine(SearchResults["Stackoverflow"].count). It gathers the data only when I'm asking for it and return a collection of the retrieved items.

luvieere