tags:

views:

486

answers:

7

I've seen lot of examples for c# Indexers, but in what way will it help me in real life situations.

I know the C# guru wouldn't have added this if it wasn't a serious feature, but i cant think of a real world situation (not the foo bar stuff) to use indexers.

Note:I realize a related question exists, but it doesn't help me much.

Thanks.

+2  A: 

Let's say you have a collection of objects that you want to be able to index by something other than the order in which it was placed in a collection. In the example below, you can see how you could use the 'Location' property of some object and using the indexer, return all objects in the collection that match you location, or in the second example, all objects that contain a certain Count() of objects.

class MyCollection {

  public IEnumerable<MyObject> this[string indexer] {
    get{ return this.Where(p => p.Location == indexer); }
  }

  public IEnumerable<MyObject> this[int size] {
    get{ return this.Where(p => p.Count() == size);}
  }
}
scottm
+4  A: 

Once .NET got generics, the biggest reason for me to implement an indexer (to implement a strongly-typed collection) went away.

Daniel Pratt
Why would the need for an indexer lessen with generics? Or do you mean that you no longer had a need to write your own collections?
Skurmedel
+3  A: 

Microsoft has an example using an indexer to treat a file as an array of bytes.

http://msdn.microsoft.com/en-us/library/aa288465(VS.71).aspx

Robert Harvey
+1  A: 

It is just syntactical sugar for collection type classes. I never had a reason to write such a class. So I think there are very rare uses of it in "real life", because the classes using it are already implemented.

Stefan Steinegger
Don’t forget that one mans rarity is another’s requirement. While they are syntacical sugar... you could say that about most of the framework. (Enum, Properties, Operator Overloading, Linq, WCF, etc.)
Matthew Whited
@Matthew: is there any difference between having an indexer or having a `GetElement` method? The indexer is shorter to use.
Stefan Steinegger
There is no difference between using a Property and a GetProperty method either. If you at the compiled code this happens for you in the back ground. Every keyword we use (beyond the OpCodes for the CPU or Runtime) is form of syntactical sugar... and I, for one, love sugar. For example... when you use a indexer in C# you declare it on the class with the this keyword. On VB.Net you just pick a property and add an input parameter.
Matthew Whited
@Matthew: Did I say that it is not useful or that I don't like it? I just said that there is nothing so special about it, just to make the usage of collection type classes nicer. I don't know what you want to tell me.
Stefan Steinegger
I didn't mean to say either. Your answer just seemed like the many I see about "unneeded" and "unwanted" features. (Along the lines of people that are complaining because LINQ syntax was added.) If you are all for indexers then we agree :)I say use them wherever you need or want to use them. This stuff is all just tools to help make our lives as developers easier.
Matthew Whited
+5  A: 

The most obvious examples, as mentioned by Skurmedel, are List<T> and Dictionary<TKey, TValue>. What would you prefer over:

List<string> list = new List<string> { "a", "b", "c" };
string value = list[1]; // This is using an indexer

Dictionary<string, string> dictionary = new Dictionary<string, string>
{
    { "foo", "bar" },
    { "x", "y" }
};
string value = dictionary["x"]; // This is using an indexer

? Now it may be relatively rare for you need to write an indexer (usually when you're creating a collection-like class), but I suspect you use them reasonably frequently.

Jon Skeet
Does this mean multiple indexers cannot exist. or in other words can they be overloaded?
Vivek Bernard
@Vivek Bernard: They can be overloaded.
OregonGhost
@OregonGhost thanks just realized that :)
Vivek Bernard
+6  A: 

The way I look at indexers is that (rightly or wrongly!), accessing something by index should be more efficient than accessing it any other way, because in some way, shape or form, the class whose indexer I'm using stores some form of index that allows it to quickly lookup values when accessed that way.

The classical example is an array, when you access element n of an array by using the code myarray[3], the compiler/interpreter knows how big (memory-wise) elements of the array are and can treat it as an offset from the start of the array. You could also "for(int i = 0; i<myarray.length; i++) { if (i = 3) then { .. do stuff } }" (not that you'd ever want to!), which would be less efficient. It also shows how an array is a bad example.

Say you had a collection class that stores, umm, DVDs, so:

public class DVDCollection
{
  private static Dictionary<string, DVD> store = new Dictionary<string, DVD>();
  private static Dictionary<ProductId, string> dvdsByProductId = new Dictionary<string, string>();

  public DVDCollection()
  {
   // ... gets DVD data from somewhere and stores it *by* TITLE in "store"
   // ... stores a lookup set of DVD ProductId's and names in "dvdsByProductid"
  }

  // Get the DVD concerned, using an index, by product Id
  public DVD this[ProductId index]  
  {
     string title = dvdsByProductId[index];
     return store[title];
  }
}

Just my 2p, but, like I said,.. I've always considered an "indexer" as being an expedient way of getting data out of something.

Rob
+2  A: 

In ASP.Net, there are a few different times where an indexer is used such as reading something from any of the Request, Session or Application objects. I've seen often where something is stored in either the Session or Application object only to be used again and again.

JB King