CSharp examples for Custom Type:Indexer
Implement a Custom Indexer
using System;/*from w w w . j a v a 2 s .c o m*/ using System.Collections.Generic; using System.Linq; public class Employee { public int DayOfWeek { get; set; } public int DailyTemp { get; set; } public int WorkingHours { get; set; } } public class EmployeeManager { private int[] temps = { 4, 3, 6, 5, 6, 7, 8 }; IList<string> daysOfWeek = new List<string>(){"Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday", "Sunday"}; public Employee this[string dow] { get { // get the day of the week index int dayindex = daysOfWeek.IndexOf(dow); return new Employee() { DayOfWeek = dayindex, DailyTemp = temps[dayindex], WorkingHours = calculateTempSoFar(dayindex) }; } set { temps[daysOfWeek.IndexOf(dow)] = value.DailyTemp; } } private int calculateTempSoFar(int dayofweek) { int[] subset = new int[dayofweek + 1]; Array.Copy(temps, 0, subset, 0, dayofweek + 1); return (int)subset.Average(); } } public class MainClass { static void Main(string[] args) { EmployeeManager forecast = new EmployeeManager(); string[] days = {"Monday", "Thursday", "Tuesday", "Saturday"}; foreach (string day in days) { Employee report = forecast[day]; Console.WriteLine("Day: {0} DayIndex {1}, Temp: {2} Ave {3}", day,report.DayOfWeek, report.DailyTemp, report.WorkingHours); } forecast["Tuesday"] = new Employee() { DailyTemp = 34 }; foreach (string day in days) { Employee report = forecast[day]; Console.WriteLine("Day: {0} DayIndex {1}, Temp: {2} Ave {3}", day,report.DayOfWeek, report.DailyTemp, report.WorkingHours); } } }