This is the main class
class Program
{
static void Main(string[] args)
{
MyArray fruit = new MyArray(-2, 1);
fruit[-2] = "Apple";
fruit[-1] = "Orange";
fruit[0] = "Banana";
fruit[1] = "Blackcurrant";
Console.WriteLine(fruit[-1]); // Outputs "Orange"
Console.WriteLine(fruit[0]); // Outputs "Banana"
Console.WriteLine(fruit[-1,0]); // Output "O"
Console.ReadLine();
}
}
and here is the class for the indexer:
class MyArray
{
int _lowerBound;
int _upperBound;
string[] _items;
public MyArray(int lowerBound, int upperBound)
{
_lowerBound = lowerBound;
_upperBound = upperBound;
_items = new string[1 + upperBound - lowerBound];
}
public string this[int index]
{
get { return _items[index - _lowerBound]; }
set { _items[index - _lowerBound] = value; }
}
public string this[int word, int position]
{
get { return _items[word - _lowerBound].Substring(position, 1); }
}
}
So, multiDimensional indexer in defined in the ‘Class MyArray’
I am not able to understand how this is working when we pass ‘-1’ as the value of ‘word’ to the indexer. The value for ‘_lowerbound’ is ‘-2’. So it means, the value for the return should be _items[-1 – (-2)], which makes it _items[1].
But actually it is pointing to -1 index of fruits i.e. Orange.
Please clear my doubt.
This is you private array
_items:This is how it appears using the indexer:
That’s correct.
That’s wrong. It is pointing to
_items[1], i.e. Orange.Indexers are a simple way to permit a class to be used like an array. Internally, you can manage the values presented in any fashion you wish.
_itemsis a zero-based array with the same length as the createdMyArrayobject.The indexer is just interpreting the index number supplied and map it against this underlying array.