Why is VBA.Collection.Count a method Why is VBA.Collection.Count a method vba vba

Why is VBA.Collection.Count a method


As far as I can tell it actually is a method:

[  odl,  uuid(A4C46780-499F-101B-BB78-00AA00383CBB),  helpcontext(0x000f7886),  hidden,  dual,  oleautomation]interface _Collection : IDispatch {    [id(00000000), helpcontext(0x000f7903)]    HRESULT Item(                    [in] VARIANT* Index,                     [out, retval] VARIANT* pvarRet);    [id(0x00000001), helpcontext(0x000f7901)]    HRESULT Add(                    [in] VARIANT* Item,                     [in, optional] VARIANT* Key,                     [in, optional] VARIANT* Before,                     [in, optional] VARIANT* After);    [id(0x00000002), helpcontext(0x000f7902)]    HRESULT Count([out, retval] long* pi4);    [id(0x00000003), helpcontext(0x000f7904)]    HRESULT Remove([in] VARIANT* Index);    [id(0xfffffffc)]    HRESULT _NewEnum([out, retval] IUnknown** ppunk);};

The "why" escapes me though.


It would be a guess, but Collection might have historically implemented count like System.Linq.Enumerable does. This might have been more historically relevant though, as now (as of 2018) the internal structure of collections has become known (discovered by the trick on VBForums).

Public Type VbCollectionKeyAndData    Key                 As String    Data                As VariantEnd Type'Private Type VbCollectionHeader    pInterface1         As Long   '  Ox00    pInterface2         As Long   '  Ox04    pInterface3         As Long   '  Ox08    lRefCounter         As Long   '  Ox0C    Count               As Long   '  Ox10    pvUnk1              As Long   '  Ox14    pFirstIndexedItem   As Long   '  Ox18    pLastIndexedItem    As Long   '  Ox1C    pvUnk4              As Long   '  Ox20    pRootTreeItem       As Long   '  Ox24 ' This is actually a pointer to what's typically thought of as the root.    pEndTreePtr         As Long   '  Ox28 ' This is effectively an EOF marker for the tree (bottom of it).  It points to the end of the VbCollectionHeader (HdrPtr + &h30)    pvUnk5              As Long   '  Ox2CEnd Type                          '  Ox30 ' Length.Private Type VbCollectionItem    Data                As Variant  '  Ox00    KeyPtr              As Long     '  Ox10     ' This is actually a String, but it's not directly accessible.  See FetchKey.    pPrevIndexedItem    As Long     '  Ox14    pNextIndexedItem    As Long     '  Ox18    pvUnknown           As Long     '  Ox1C    pParentItem         As Long     '  Ox20    pRightBranch        As Long     '  Ox24    pLeftBranch         As Long     '  Ox28    bFlag               As Boolean  '  Ox2CEnd Type                            '  Ox30 ' Length. (boolean padded to 4)

We can see that the VbCollectionHeader contains the Count of items in the collection, so it's anticipated that, today, Count is kept track of internally and thus behaves more like a property than a method.