Mega Code Archive

 
Categories / C# Tutorial / Class
 

Define getter only indexer

using System; public class Employee {   private string firstName;   private string lastName;   public Employee(string firstName, string lastName)   {     this.firstName = firstName;     this.lastName = lastName;   }   public string this[int index]   {     get     {       switch (index)       {         case 0:           return firstName;         case 1:           return lastName;         default:           throw new IndexOutOfRangeException();       }     }   } } class MainClass {   public static void Main()   {     Employee myEmployee = new Employee("T", "M");     Console.WriteLine("myEmployee[0] = " + myEmployee[0]);     Console.WriteLine("myEmployee[1] = " + myEmployee[1]);   } } myEmployee[0] = T myEmployee[1] = M