The standard for collections lets you describe two kinds of collections, depending on whether it makes sense for the collected objects to exist outside the collection.
In some cases, it is not logical for an object to exist independently of its collection. For example, an application's Documents collection contains all Document objects currently open. Opening a document means adding it to the collection, and closing the document means removing it from the collection. All open documents are part of the collection. The application cannot have open documents that are not part of the collection. The relationship between the collection and the members of the collection can be shown in the following ways:
Set MyDoc = Documents.Add
Set SomeDoc = Documents(3)
SomeDoc.Close
In other cases, it is logical for the objects to exist outside the collection. For example, a Mail application might have Name objects, and many collections of these Name objects. Each Name object would have a user's e-mail name, full name, and possibly other information. The e-mail name and full name would likely be properties named EmailName and FullName.
Additionally, the application might have the following collections of Name objects.
The collections of Name objects could be indexed by using either EmailName or FullName.
For these collections, the Add method does not create an object because the object already exists. Therefore, the Add method should take an object as an argument, and should not return a value.
Assuming the existence of two collections (AddressBook and ToList), a user might execute the following code to add a Name object to the ToList collection:
Dim Message as Object
Dim AddressBook as Object
Dim NameRef as Object
.
.
.
Set NameRef = AddressBook.Names("Fred Funk")
Message.ToList.Add NameRef
The Name object already exists and is contained in the AddressBook collection. The first line of code obtains a reference to the Name object for "Fred Funk" and points to NameRef. The second line of code adds a reference to the object to the ToList collection. No new object is created, so no reference is returned from the Add method.
Unlike the relationship between Documents and Document, there is no way for the collected object (the Name) to know how to remove itself from the collections in which it is contained. To remove an item from a collection, use the Remove method, as follows:
Message.ToList.Remove("Fred Funk")
This line of code removes the Name object that has the FullName "Fred Funk." The "Fred Funk" object may exist in other collections, but they will be unaffected.