When should you use C# indexers?

后端 未结 10 1624
终归单人心
终归单人心 2020-12-06 10:10

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

10条回答
  •  难免孤独
    2020-12-06 10:30

    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.

提交回复
热议问题