Indexers in C#
Indexers allows class to Index like an array.
Here is an example of Integer Index as well as String Index.
class IndexersDemo
{
int[] arr = new int[100];
Dictionary<String, String> strArr = new Dictionary<string, string>();
public IndexersDemo()
{
}
public int this[int i]
{
get{return arr[i];}
set{arr[i]=value;}
}
public String this[String str]
{
get { return strArr[str]; }
set { strArr[str] = value; }
}
void Display()
{
foreach (int i in arr)
{
Console.Write(i);
}
foreach (KeyValuePair<String, String> strkeyVal in strArr)
{
Console.WriteLine("{0} {1}",strkeyVal.Key,strkeyVal.Value);
}
}
public static void Main()
{
IndexersDemo id = new IndexersDemo();
id[0] = 100;
id[01] = 1000;
id[02] = 10000;
id["Hello"] = "World!";
id["INDIA"] = "Incredible";
id["UK"] = "Great Britian";
id["US"] = "United States of America";
id.Display();
}
}
{
int[] arr = new int[100];
Dictionary<String, String> strArr = new Dictionary<string, string>();
public IndexersDemo()
{
}
public int this[int i]
{
get{return arr[i];}
set{arr[i]=value;}
}
public String this[String str]
{
get { return strArr[str]; }
set { strArr[str] = value; }
}
void Display()
{
foreach (int i in arr)
{
Console.Write(i);
}
foreach (KeyValuePair<String, String> strkeyVal in strArr)
{
Console.WriteLine("{0} {1}",strkeyVal.Key,strkeyVal.Value);
}
}
public static void Main()
{
IndexersDemo id = new IndexersDemo();
id[0] = 100;
id[01] = 1000;
id[02] = 10000;
id["Hello"] = "World!";
id["INDIA"] = "Incredible";
id["UK"] = "Great Britian";
id["US"] = "United States of America";
id.Display();
}
}
Tags: Indexers in C#,Indexer C# feature,INT indexer in C#,String Indexer in C#
No comments:
Post a Comment