What is Indexer in C#?

Technology CommunityCategory: C#What is Indexer in C#?
VietMX Staff asked 3 years ago

An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this class behaves similar to a virtual array. You can then access the instance of this class using the array access operator ( ). Indexers can be overloaded. Indexers can also be declared with multiple parameters and each parameter may be a different type. It is not necessary that the indexes have to be integers. C# allows indexes to be of other types, for example, a string.

Consider:

class IndexedNames {
	private string[] namelist = new string[size];

	public string this[int index] {
		get {
			string tmp;

			if (index >= 0 && index <= size - 1) {
				tmp = namelist[index];
			} else {
				tmp = "";
			}

			return (tmp);
		}
		set {
			if (index >= 0 && index <= size - 1) {
				namelist[index] = value;
			}
		}
	}
}