Title: Give a class default indexer properties in C#
An indexer property is a property that other code can use inside square brackets to access some value provided by the class, much as you can use the index of an array. Unlike an array, a class's indexer need not be an integer. Furthermore you can overload the indexer to provide more than one indexer for a class.
The following code shows a GradeCollection class. This is really just a wrapper for a Dictionary that holds student names and their grades.
public class GradeCollection
// A Dictionary to hold student grades.
private Dictionary Grades =
// The default indexer property.
// Get or set a student's grade.
public int this[string student]
Grades[student] = value;
// A default indexer property.
// Return a list students with this grade.
public List this[int score]
List students = new List();
foreach (string name in Grades.Keys)
if (Grades[name] == score) students.Add(name);
The class contains a Dictionary object to hold the students' names and grades.
The two methods named this that uses square brackets are indexers. The first indexer takes a string parameter (a student's name) and returns that student's grade. It provides get and set methods that simply delegate their work to the Dictionary object.
The main program uses the following line of code to use this indexer to display a student's grade.
txtGrade.Text = Grades[txtStudent.Text].ToString();
The code Grades[txtStudent.Text] uses the indexer to get the grade for the student whose name is in the txtStudent TextBox. The code converts the returned grade into a string and displays it in the txtGrade TextBox.
The following code shows how the program uses this indexer to set a student's grade.
Grades[txtStudent.Text] = int.Parse(txtGrade.Text);
The left hand side of the statement represents the student's grade. This statement sets the grade equal to the value in the txtGrade TextBox.
The class's second indexer takes an integer score as a parameter and returns a collection of students with grades that match that score.
The indexer's code loops through the Grades dictionary's keys. If the corresponding student's grade matches the target value, the code adds the student's name to the result list. After it has looped over all of the student names, the indexer returns the list.
Note that I don't really recommend that you make such an indexer. It doesn't seem too useful in practice. This example just shows how to make multiple overloaded indexers. Notice also that the second indexer is read-only. You can't use a List as an index to set a bunch of students' scores all at once. (Although writing that piece of the indexer might be a good exercise.)
Download the example to experiment with it and to see additional details.