views:

103

answers:

2

To have an indexer we use the following format:

class ClassName
{
    DataType[] ArrayName = new DataType[Length]; 

    public DataType this[int i]
    {
        get { return ArrayName[i]; }
    }
}

For the sake of simplicity I used the format, even though we can go for a custom indexer also. According to my understanding, we are keeping a propery array that is indexed.

My question is :

  1. Is it a templated property?
  2. When and where could we achieve high degree code optimization using this indexer?
+1  A: 

This isn't a templated property, it is a parameterful property - that is a property that accepts a parameter argument.

This boils down to simply a get_Item(Int32) method in place of a get_Item() method that would normally be emitted by the compiler in place of a parameterless property. As such this doesn't open up much opportunities for optimization.

Andrew Hare
+1  A: 

It is not about code optimization.
You could write a method in your class that can get you the item from the collection it holds.

e.g.

public DataType GetItemByIndex(int i)
{
}

Indexers are in a way, "syntactic sugar", to let users treat the instance as an array or collection.

shahkalpesh