Sunday, January 22, 2012

Indexers

Indexers allows client code to access a collection item of a class (or interface or structure) by
using object of class as an array.
Syntax -
public int this[int x]  
{
       //  get and set accessors
}

Terminology -
A. Indexers defined by using this keyword, denotes current instance.
B. Indexer must have a parameter of any data type, else compiler will through the error.
C. Object of class behave like an array for indexer.
D. Indexer can't be static it always be the instance member.
E. Indexer can be overloaded, you can have multiple indexers with different signatures.
F. Provides syntactical benefit.
G. Indexers can be used with structures same as used with classes.
H. Indexers declared in an interface enforces to implement same signature(parameter and return type, not access modifier) indexers in Classes those implement that interface.
I. Syntax of indexer in an interface, its not have access modifier because they are public by default and do not have body of accessors because interface only declares members not defines.
int this[int index]
    {
        get;
        set;
    }


Example -
class Indexers
{
        public Indexers()
        { }

//Temprature taken at different time
float[] Temp = new float[]{56.2F, 56.7F, 56.5F, 56.9F, 58.8F,
61.3F, 65.9F, 62.1F, 59.2F, 57.5F};
public float this[int index]
{
get
{
        return Temp[index];
}
set
{
        Temp[index] = value;
}
}

//Weekdays
string[] days = new string[] { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };
private string Getday(string gday)
{
    foreach (string tDay in days)
    {
        if (tDay == gday) return tDay;
    }
    return "Invalid day";
}
public string this[string day] //Overloading of indexers
{
    get
    {
        return Getday(day);
    }
}
}
public class CallIndexers
{
    public static void Main()
    {
        Indexers ObjIndexers = new Indexers();
        Console.WriteLine(ObjIndexers["Wed"]); //Output : Wed

        Console.WriteLine(ObjIndexers[2]); //Output : 56.5F
        ObjIndexers[5] = 60.02F;
        Console.WriteLine(ObjIndexers[5]); //Output : 60.02F
    }
}

No comments:

Post a Comment

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...