My C++ programmers out there should immediately recognize what these are.
indexers
are a mechanism by which we can use square bracket notation [] to access attributes of a class. Usually an
attribute defined as an array but sometimes a collection of similar individual attributes. In other words:
this is the subscript operator overload from C++. While the argument to
indexers
doesn't have to be integers, it almost always will be.
Let's take a look at an example of how this is implemented:
public class Course
{
private Student[] enrolled;
private ushort size, capacity;
// This data type isn't mocking your height — it's an unsigned short integer
public Student this[int index]
{
get { return enrolled[index]; }
set { enrolled[index] = value; }
}
}
This allows me to write code such as
Course thisClass;
thisClass[0] = myFirstStudent;
In order to directly access the private
enrolled attribute of objects
instantiated from
Course class. Now, I would have included checks to ensure that
index contains a legal value (between 0 and "capacity - 1"), but I'm formatting
this code out in HTML, which is annoying enough as is.