CSharp examples for Custom Type:Indexer
Overload indexer
using System;//w ww.j a v a2 s . c o m class BirthsList { private int[] births; private string[] birthsRegionNames; public BirthsList(params string[] regionNames) { birthsRegionNames = regionNames; births = new int[regionNames.Length]; for (int i = 0; i < regionNames.Length; i++) { births[i] = 0; } } public int this [int index] { get { if (index >= 0 && index < births.Length) { return births[index]; } else { Console.WriteLine("Incorrect index provided"); return -1; } } set { if (index >= 0 && index < births.Length) { births[index] = value; } else { Console.WriteLine("Incorrect index provided"); } } } public int this [string indexName] { get { return this [NameToIndex(indexName)]; } set { this[NameToIndex(indexName)] = value; } } private int NameToIndex(string indexName) { for (int i = 0; i < birthsRegionNames.Length; i++) { if (birthsRegionNames[i].ToUpper() == indexName.ToUpper()) return i; } Console.WriteLine("Could not find region name"); return -1; } public int TotalBirths { get { int sum = 0; foreach (int amount in births) { sum += amount; } return sum; } } public int Average { get { return TotalBirths / births.Length; } } } class BirthListTester { public static void Main() { BirthsList birthsListUSA = new BirthsList("California", "New York", "Texas"); birthsListUSA["California"] = 1; birthsListUSA[1] = 2; birthsListUSA[2] = 3; Console.WriteLine("Number of births in Texas: {0}", birthsListUSA["Texas"]); Console.WriteLine("Total births: {0} Average births: {1}", birthsListUSA.TotalBirths, birthsListUSA.Average); } }