Indexer Methods in C#

// Indexers allow you to access items in an array-like fashion.
class Program
{
  static void Main(string[] args)
  {
 
    PersonCollection allPeople = new PersonCollection();
 
    // Add objects with indexer syntax.
    allPeople[0] = new Person("Homer", "Simpson", 40);
    allPeople[1] = new Person("Marge", "Simpson", 38);
    allPeople[2] = new Person("Lisa", "Simpson", 9);
    allPeople[3] = new Person("Bart", "Simpson", 7);
    allPeople[4] = new Person("Maggie", "Simpson", 2);
 
    // Now obtain and display each item using indexer.
    for (int i = 0; i < allPeople.Count; i++)
    {
      Console.WriteLine("Person number: {0}", i);
      Console.WriteLine("Name: {0} {1}",
        allPeople[i].FirstName, allPeople[i].LastName);
      Console.WriteLine("Age: {0}", allPeople[i].Age);
      Console.WriteLine();
    }
  }
}
// Add the indexer to the existing class definition.
public class PersonCollection : IEnumerable
{
  private ArrayList People = new ArrayList();
 
  // Custom indexer for this class.
  public Person this[int index]
  {
    get { return (Person)People[index]; }
    set { People.Insert(index, value); }
  }
...
}

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.