Dear,

An indexer is a member of class that enables an object to be indexed in the same way as an array.

Consider the following code:

using System;

public class Date
{
    int d, m, y;

     // Constructors
    public Date()
    {
        d = DateTime.Now.Day;
        m = DateTime.Now.Month;
        y = DateTime.Now.Year;
    }
    public Date(int d, int m, int y)
    {
        this.y = y;
        this.m = m;
        this.d = d;
    }

    // Properties
    public int Day
    {
        get { return d; }
        set { d = value; }
    }
    public int Month
    {
        get { return m; }
        set { m = value; }
    }
    public int Year
    {
        get { return y; }
        set { y = value; }
    }

    public string DMY
    {
        get
        {
            return d + "-" + m + "-" + y;
        }
    }
    public string MDY
    {
        get
        {
            return m + "-" + d + "-" + y;
        }
    }

    // Indexers  
    public int this[string i]
    {
        get
        {
            if (i == "day")
                return d;
            else
                if (i == "month")
                    return m;
                else
                    return y;
        }
        set
        {
            if (i == "day")
                d = value;
            if (i == "month")
                m = value;
            if (i == "year")
                y = value;
        }
    }
    public int this[int i]
    {
        get
        {
            if (i == 0)
                return d;
            else
                if (i == 1)
                    return m;
                else
                    return y;
        }
        set
        {
            if (i == 0)
                d = value;
            if (i == 1)
                m = value;
            if (i == 2)
                y = value;
        }
    }

}


class MainApp
{
    static void Main()
    {
        Date k = new Date();

        Console.WriteLine(k.DMY);
        Console.WriteLine(k.MDY);
        k.Day = 8;
        Console.WriteLine(k.DMY);

        k[0] = 10;
        k[1] = 3;
        k[2] = 2010;

        Console.WriteLine(k[0]);

        k["month"] = 2;

        Console.WriteLine(k["day"] + "-" + k["month"] + "-" + k[2]);

       // Another example with string object
        string name = "Hello";
        Console.WriteLine(name[1]);
    }
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

This article has been dead for over six months. Start a new discussion instead.