Bad Example in indexers lesson ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

Bad Example in indexers lesson ?

From the example here (the second one from the indexer lesson), I really don't get how indexers work, or how they are useful. From my point of view, in this example, they are essentially declaring an array of string in an object, and then modifying and display strings from this array. Why is an indexer needed here ? And they say an indexer allows instances of a class to be indexed, like in an array. But why not have an array of "class you're trying to index" type and store he class instances in it ? Would anyone happen to have a clearer explanation ? I must say, up unitl now the lessons were very clear, but I'm a bit puzzled on this one.

5th Feb 2017, 11:43 PM
Lucas Martinez
Lucas Martinez - avatar
2 Answers
+ 8
First of all, you need to see the difference between an array and an indexer: An array is a collection of variables of the same type that are referred to by a common name and which, when called, go directly to the case you asked through the index (of the array) Indexers: An indexer allows an object to be indexed like an array BUT they are principle used to support the creation of specialized arrays that are subject to one or more constraints. So actually you would say, why not use only array because it's seems more easy to use and why change something that you know already and seems the best option ? Just remember that 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 ([ ]). Declaration of behavior of an indexer is to some extent similar to a property. similar to the properties, you use get and set accessors for defining an indexer. However, properties return or set a specific data member, whereas indexers returns or sets a particular value from the object instance. In other words, it breaks the instance data into smaller parts and indexes each part, gets or sets each part. By the way, you will find indexers more easier when you could use more that one with generic function (last chapter) Hope it helped
7th Feb 2017, 2:27 AM
Matthieu Lanvert
Matthieu Lanvert - avatar
0
Wow tanks a bunch, that was really helpful :)
7th Feb 2017, 11:16 AM
Lucas Martinez
Lucas Martinez - avatar