15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

346<br />

Using a Collection<br />

Because a collection is nothing more than a data structure, like an array, the<br />

first step to creating a collection is to declare a variable as a collection, such<br />

as the following Visual Basic.NET example shows:<br />

Dim MyStuff as New Collection<br />

This command simply identifies a MyStuff variable as a collection data<br />

structure. The New command tells the computer to create a new collection.<br />

Adding data to a collection<br />

When you first create a collection, it contains zero items. Each time you add<br />

a new chunk of data to a collection, it expands automatically so you never<br />

have to specify a size be<strong>for</strong>ehand (like an array) or deliberately resize it later<br />

(like a dynamic array).<br />

To add data to a collection in Visual Basic.NET, you must use an Add command<br />

like this:<br />

Dim MyStuff as New Collection<br />

MyStuff.Add (“Dirty socks”)<br />

Each time you add another element to a collection, the computer tacks<br />

that new data at the end of the collection. So if you added the string Dirty<br />

socks, the number 7348, and the number 4.39, the collection would look like<br />

Figure 3-1.<br />

Figure 3-1:<br />

Collections<br />

expand<br />

automatically<br />

each<br />

time you<br />

store new<br />

data.<br />

1<br />

Dirty socks Each time you add an item to a collection . . .<br />

1 2<br />

Dirty socks 7348 . . . the collection grows automatically.<br />

1 2 3<br />

Dirty socks 7348 4.39<br />

Dim MyStuff as New Collection<br />

MyStuff.Add (“Dirty socks”)<br />

MyStuff.Add (7348)<br />

MyStuff.Add (4.39)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!