.NET interview questions: - Explain in details about Indexer and can we have static indexer in C#?
Many time classes have contained (aggregated or composed) collections. For example in the below code you can see we have a customer class which has an address collection.
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.
Now on the client side your code would look something as shown below.
Now the above code is great but how about simplifying things further. In more simplified as shown in the below code. In other words we want to INDEXED the class itself.
You can see the below image where we can have two overloaded indexers "PinCode" and "PhoneNumber".
This can be achieved by using an indexer. There are two things we need to remember about indexer:-
- "Indexer" is defined by using "this" keyword.
- "Indexer" is a property so we need to define set and get for the same.
Below is the code implementation for indexer. You can see we have used "this" keyword with two overloaded function one which will fetch us address by using the "phonenumber" and the other by using "pincode".
Once you put the above "indexer" code you should be able to access the address collection from the customer object using an indexer "" as shown in the below figure.
Summarizing in one sentence: - Indexers helps us to access contained collection with in a class using a simplified interface. It's a syntactic sugar.
Static indexer in C#:
No we cannot have Static indexer in C#.
Also see .NET interview questions video on indexers in C# (Csharp): -