Indexed properties or indexers, allows „array-like access to groups of items“. In other words, if a class makes use of array or other collection types, it is recommended to use indexers for accessing the values of these internal collections. Whereas the standard C# Properties are used to access single values in classes, an indexed property is used to encapsulate a set of values.

Other important things to remember about Indexers are:

  1. public EmployeeNumber this [PhoneNumber number] { ………………. }
  2. public PhoneNumber this [ EmployeeNumber number] { ……………..…}
  1. public int this [string id ] {……………..} //OK.

  1. EmployeeIndexer empIndexer ;// empIndexer contains an indexer
  2. GetEmpId(ref empIndexer[1]) ; // Compile time error.

Let’s understand the whole new concept with an example.

We have a list of Person. Person class contains Name and ID. Indexer as highlighted in the code snippet below expects a Name to be looked in to the list of persons and it returns the ID the person found.

  1. public class Person
  2. {
  3. #region member variable
  4. private Person[] _listOfPersons;
  5. private string _name;
  6. private int _id;
  7. #endregion
  8. #region member function
  9. /// <summary>
  10. /// get the list of the person
  11. /// this list may also come from the database
  12. /// </summary>
  13. public void GetPersonList()
  14. {
  15. _listOfPersons = new Person[] { new Person() { _id = 1, _name = "James" }, new Person() { _id = 2, _name = "Kevin" } };
  16. }
  17. #endregion
  18. #region indexer
  19. public int this[string name]
  20. {
  21. get { return (from a in _listOfPersons where String.Equals(a._name, name) select a._id).FirstOrDefault(); }
  22. }
  23. #endregion
  24. }
Some points which need attention are:

To define the indexer, a notation that is cross between a property and an array is used. Indexers are defined with the this keyword and type of the value returned by the indexer. And the most important is to specify the type of the value to use as the index into the indexer between square brackets.

To use retrieve a value from a collection, one needs to pass the value that need to be matched in the collection. There gives different ways to look in to the collection but in my case I have kept it simple and used a LINQ statement.

The code has been attached for the reference.