Reputation: 91
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 :
Upvotes: 0
Views: 406
Reputation: 33476
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.
Upvotes: 2
Reputation: 351476
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.
Upvotes: 1