Real world use cases for C# indexers?

后端 未结 14 1498
时光说笑
时光说笑 2020-12-04 15:26

I\'ve seen lot of examples for c# Indexers, but in what way will it help me in real life situations.

I know the C# guru wouldn\'t have added this if it wasn\'t a ser

14条回答
  •  抹茶落季
    2020-12-04 16:15

    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.

提交回复
热议问题