Indexes are generally used to access a specific element or setting a value to a specific element in a collection or a array. But indexes can be used on classes/structs or interfaces to provide an array like access. Let’s consider the following Fruit class.
It’s pretty simple class, I have an array of type string and in the constructor I am initializing the array with a given length. So this is how I would access the Items array from outside.
Now if we can omit the part where we are accessing Items array through fruits.Items and can access it like fruits, fruits etc. isn’t that great. And that’s where the Indexes can be real handy. And here is how we can define an Index in the Fruit class.
Here I have a private string array and in the constructor I am initializing the array with a given length. I have another property which exposes the length of the array. And then I have the Index syntax.
Now let’s see how we can access items array through the Index defined for the class.