Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make my custom class compatible with For Each?

Tags:

vbscript

Is it possible to make a custom container class implemented purely in VBScript (no COM objects) work with the For Each statement? If so, what methods must I expose?

like image 782
jmbpiano Avatar asked May 11 '15 18:05

jmbpiano


People also ask

How does C++ foreach work?

The foreach loop in C++ or more specifically, range-based for loop was introduced with the C++11. This type of for loop structure eases the traversal over an iterable data set. It does this by eliminating the initialization process and traversing over each and every element rather than an iterator.

Which interface a type must have implemented to be iterated in foreach loop c#?

The return type of this method is IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>. Which means by using iterator compiler will automatically create IEnumerable or IEnumerator interface for you there is no need to implement IEnumerable or IEnumerator interface in your class for using a foreach loop.

When we create a custom collection class if you want to iterate through the collection using a foreach loop which interface has to be implemented?

The IEnumerator interface provides iteration over a collection-type object in a class. The IEnumerable interface permits enumeration by using a foreach loop.

Which of the following interface enables foreach style iteration over generic collections?

IEnumerable Returns the IEnumerator interface for a given object. IEnumerator Enables foreach style iteration of subtypes.


1 Answers

In short, no

Why? To create an enumerable collection class to get something like

Class CTest
    ....
End Class

Dim oTest, mElement
    Set oTest = New CTest
    ....
    For Each mElement In oTest
        ....
    Next 

the class MUST follow some rules. We will need the class to expose

  • A public readonly property called Count

  • A public default method called Item

  • A public readonly property called _NewEnum, that should return an
    IUnknown interface to an object which implements the IEnumVARIANT interface and that must have the hidden attribute and a dispatch ID of -4

And from this list or requirements, VBScript does not include any way to indicate the dispatch ID or hidden attribute of a property.

So, this can not be done

The only way to enumerate over the elements stored in a container class is to have a property (or method) that returns

  • an object that supports all the indicated requirements, usually the same object used to hold the elements (fast, but it will expose too much information)

  • an array (in VBScript arrays can be enumerated) holding references to each of the elements in the container (slow if the array needs to be generated on call, but does not return any non required information)

like image 144
MC ND Avatar answered Oct 26 '22 21:10

MC ND