May 4, 2011

Overloaded Indexer example in C#

Below is the sample code which is for overloaded indexer of a class
I/P parameter has to be unique for indexer in the same class


using System;
using System.Collections;
using System.Collections.Generic;


class testIndexer
{
    public  Hashtable Address = new Hashtable(5);
    public  List <object> obj=new List <object >(5);
    public object  this[int index]
    {
        get
        {
            return obj[index];
        }
        set
        {
            obj[index] = value;
        }
    }
    
    public string this[String key]
    {
        get
        {
            return Address[key].ToString();
        }
        set
        {
            Address[key] = value;
        }
    }


}


class MyClient
{
    public static void Main()
    {
        testIndexer tc = new testIndexer();
        tc.obj.Add(1);
        tc.obj.Add("ABC");
        tc.obj.Add(1.5);
        tc.obj.Add(22);
        tc.obj.Add(13);




        testIndexer tc1 = new testIndexer();
        tc1.Address.Add("Area", "worli");
        tc1.Address.Add("City", "Mumbai");
        tc1.Address.Add("Country", "India");
        




        Console.WriteLine("{0},{1},{2},{3},{4}", tc[0], tc[1], tc[2], tc[3], tc[4]);


        
        Console.WriteLine("{0},{1},{2}", tc1["Area"], tc1["City"], tc1["Country"]);
    }
}

Below 'll be the o/p

No comments:

Post a Comment