Thursday, March 5, 2015

C# : Indexes in Classes

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.
public class Fruit
{
    public Fruit(int length)
    {
        this.items = new string[length];
    }

    private string[] items;
 
    public string[] Items
    {
        get { return items; }
        set { items = value; }
    }
}
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.
static void Main(string[] args)
{
    Fruit fruits = new Fruit(10);
    fruits.Items[0] = "Apple";
    fruits.Items[1] = "Orange";
}
Now if we can omit the part where we are accessing Items array through fruits.Items and can access it like fruits[0], fruits[1] 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.
public class Fruit
{
    private string[] items;
 
    public Fruit(int length)
    {
        this.items = new string[length];
    }
 
    public string this[int index]
    {
        get { return items[index]; }
        set { items[index] = value; }
    }
 
    public int Length
    {
        get
        {
            return items.Length;
        }
    }
}
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.
Fruit fruits = new Fruit(5);
fruits[0] = "Apple";
fruits[1] = "Orange";
 
for (int i = 0; i < fruits.Length; i++)
{
    Console.WriteLine(fruits[i]);
}
image
Result
Isn’t that great.

Happy Coding.

Regards,
Jaliya