Unlike C++, .NET Framework facilitates accessing individual elements in the custom collection while implementing and interfaces. For example, it is a hassle free job to access types collected in an . This had been eased by class while implementing and interfaces.
Before continuing, let me explain the structure, members of the , interfaces. The interface contains an abstract member function called and return an interface on any success call. This interface will allow us to iterate through any custom collection.
interface is meant to be used as accessors and is not helpful to make any changes in the collection or elements of the collection.
Presumably, any element in a collection can be retrieved through its index property. But instead of element index, the provides two abstract methods and a property to pull a particular element in a collection. And they are , and .
See the figure. This is how it works.
The signature of is as follows:
Members of IEnumerator Interface
The signature of members is as follows:
Refer to the figure which depicts three object instances in the custom collection.
The method returns a type and helps you to position the pointer just before the start point. Refer to the figure where I have three instances and the pointer is in the empty position. This method will also help you to reset the iteration pointer anywhere from the start position. For example, you are in the second instance and need to start from first. In addition to all, the method has to be called after any successive addition, deletion of elements in the collection.
The method will help you to position the location of the required element in the collection while sending a flag value. And its objective is to inform the caller whether the current position holds any value or not. If it has, then will return or return in case there is no value. In addition, the will help you to position the first element in the collection after calling the method.
The property of interface will return an individual element of a given collection. This property is used to return an element in the collection by using the specified location pointer.
I.e. If you want to iterate through the collection, you need to call the method just before the . Otherwise, it will return the same element that the property previously returns as output. In addition, if you are trying to enumerate for the first time, then you need to call methods and properties in this hierarchy: - > -> .
Personally, I feel the code which is available along with the article is explanatory enough to give a clear picture for further tunings.
The aforementioned code is a part in my first example and tries to access the individual elements without implementing the required interfaces. But this code will fail to compile and the message is:
I address the above compilation error in the second example while implementing , interfaces.