Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0126 Your own indexer

The following code uses the indexer to access each week day. using System; class Week { string[] days = new string[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; public string this[int i] { get { return days[i]; } set { days[i] = value; } } } class Program { static void Main(string[] args) { Week w = new Week(); Console.WriteLine(w[2]); } } The output: Wednesday The indexer can have the following modifiers: static public internal private protected new virtual abstract override sealed unsafe extern