I am new to VB in general. I am going through some old VB code and I see statements like -
Addr.AddrType(CStr(0)).A_Type = " "
Why does the integer 0 have to be converted to a string?
Note that Addr is defined as
Public Addr As clsAddressDetail
AddrType is defined as a collection
Public AddrType As New Collection
The Collection class being used here has what is effectively an overloaded indexer. My emphases:
Returns a specific element of a Collection object either by position or by key. Read-only.
Default Public ReadOnly Property Item( _ ByVal { Key As String | Index As Integer | Index As Object } _ ) As ObjectParameters
Key
A unique String expression that specifies a key string that can be used, instead of a positional index, to access an element of the collection. Key must correspond to the Key argument specified when the element was added to the collection.
Index
(A) A numeric expression that specifies the position of an element of the collection. Index must be a number from 1 through the value of the collection's Count Property (Collection Object). Or (B) An Object expression that specifies the position or key string of an element of the collection.
So, if you ask for AddrType(0), you are asking for the zeroth member of the collection, which for this 1-based collection is an error. But if you ask for AddrType("0"), you are asking for that member which was added with Key "0". Any string can be used as a key - it's just that the particular string used here is the string representation of a number.
Incidentally, stylistically I would say writing CStr(0) rather than "0" isn't particularly nice...
The CStr() function there is used to access a specific member of the AddrType collection. Collections can be referenced either by a numeric index or by a string key value. So the short answer is, integers don't have to be converted to strings to access collection members. Why this particular coder chose to use "0" for a key value is unknown; it's certainly no more descriptive than using a numeric index, which would be the only advantage to the string key value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With