When should you use C# indexers?

Ian Davis picture Ian Davis · Jul 23, 2010 · Viewed 25k times · Source

I'd like to use indexers more, but I'm not sure when to use them. All I've found online are examples that use classes like MyClass and IndexerClass.

What about in a school system where there are Students and Teachers, and each Teacher has a list of Students that they're in charge of - any need for indexers in that scenario? For simplicity's sake: each Student can only belong to one Teacher.

Answer

Shivprasad Koirala picture Shivprasad Koirala · Dec 24, 2013

Heres a video i have created http://www.youtube.com/watch?v=HdtEQqu0yOY and below is a detailed explanation about the same.

Indexers helps to access contained collection with in a class using a simplified interface. It’s a syntactic sugar.

For instance lets say you have a customer class with addresses collection inside it. Now let’s say we would like to like fetch the addresses collection by “Pincode” and “PhoneNumber”. So the logical step would be that you would go and create two overloaded functions one which fetches by using “PhoneNumber” and the other by “PinCode”. You can see in the below code we have two functions defined.

Customer Customers = new Customer();
Customers.getAddress(1001);
Customers.getAddress("9090");

If you use indexer you can simplify the above code with something as shown in the below code.

Customer Customers = new Customer();
Address o = Customers[10001];
o = Customers["4320948"];

Cheers.