Collections and Generics Tutorial – Visual Basic.NET

Arrays and Collections

The .NET Framework includes a variety of different collections that you can use to organize groups of related data. These classes include ArrayList, Queue, Stack, StringCollection, and BitArray. ArrayList, Queue, and Stack can be used with any class, including custom classes. StringCollection can only be used with strings, and BitArray can only be used with Boolean values.

Dictionaries provide functionality similar to collections, but they use name/value pairs to access data. The .NET Framework provides the Hashtable, SortedList, StringDictionary, ListDictionary, HybridDictionary, and NameValueCollection dictionaries to support a variety of different data types and performance requirements.

This lesson describes the most useful Collection and Dictionary classes.

At the end of this lesson, you will be able to:

  • Use collections and choose the best collection class for different requirements
  • Use dictionaries and choose the best dictionary class for different requirements


In Visual Basic, you declare an array by using parentheses. Once you create an array, you can access the contents of an array by specifying the element number (starting with 0) or iterate through every element in the array by using a For Each loop.

An array of a type can have different methods than the type itself. For example, an array of integers has the Average method (which returns the average of the integers in the array), the Min and Max methods (which return the lowest and highest elements), and the Sum method (which returns the total of the elements).

The Array class has a variety of static members you can use to perform different actions on elements in an array. The following code sample demonstrates using the Array.Sort method, which sorts the contents of an array if the type supports sorrting. The next topic lists other Array methods.

' Declare and initialize an array. 

Dim ar() As Integer = {3, 1, 2}

' Call a shared/static array method. 


' Display the result two different way. 

Console.WriteLine("{0}, {1}, {2}", ar(0), ar(1), ar(2))

For Each i As Integer In ar



Array Methods

This table shows the most useful static methods provided by the Array class. You can use these to process arrays. Some methods, such as Sort, only work with specific types of elements. If you call Array.Sort using an array of elements that do not support the IComparable interface, the runtime will throw an exception.




Searches an array for a value. The array must already be sorted.


Copies a range of elements to a second array, performing casting and boxing (as described in Module 1) as required.


Searches for an element within an array, and returns the first occurence it finds. To find all occurences, use the FindAll method.


Finds all elements that match the specified conditions.


Reverses the order of the elements in an array.


The .NET Framework provides a variety of different collection classes that you can use for different circumstances. ArrayList is the most versatile, but it lacks the specialized features of the other classes.



ArrayList A colleciton that dynamically grows. You can add any type to an ArrayList, including multiple types to a single instance of ArrayList.
BitArray An array of Boolean values.
Hashtable A collection of key/value pairs.
Queue A first-in, first-out collection. Queue provides the Enqueue method to add elements to the collection, the Dequeue method to remove elements from the collection, and the Peek method to access an element without removing it.
Stack A last-in, first-out collection. Stack provides the Push method to add elements to the collection, the Pop method to remove an element from the collection, and the Peek method to access an element without removing it.
SortedList A collection of key/value pairs that are sorted by the key. You can access elements by using the key.

Demonstration: Using Arrays and Collections

Watch this video about using arrays and collections in C#. Be sure to watch it full-screen in HD. You can download the source code solution for this project here: Shopping Cart Project in C#

Here’s the full transcript:

I’m going to create a console application that simulates a shopping cart, allowing you to add items to it, and then sort those items in different ways. Then, I will demonstrate the Queue and Stack collections just to show how they work.

First we need to create an Item class. It’s going to have two properties: Title and Price. Price is going to be a Double. So, pretty simple.

From the Item class I’m going to derive two types of classes that will work with the Book and CD classes. While we’re creating the application we’ll be able to add either the Book or the CD class to an array and then work with them in the same way because they’re derived from the same base class.

Both of these are going to inherit from the Item class. I’m going to add one additional attribute. For the books, I’ll add the ISBN, which is a number that uniquely identifies a book. I will create a constructor.

This constructor is going to define all of the properties of the object.

Now I’m going to create the CD class, and I’ll jump through this so you don’t have to wait for me to type. So, there’s the CD class. Now, we’re ready to actually work with it. The first thing I want to do is to create an ArrayList that allows us to store a combination of books and CDs. Then, we will iterate through that ArrayList to display them all to the console.

I will call the ArrayList Items. And though you wouldn’t do this in the production world, I’m simply going to manually type in descriptions for the different items and add them to the array. I use the Windows Vista Resource Kit as the first book—that’s a book I worked on. And, if you can’t tell, I am copying the ISBN—I do not have that memorized.

And, of course, the new Windows 7 Resource Kit. Now, I’ll add two CDs to demonstrate that you can work with different types of objects, so long as they are derived from the same class. Really, you can add anything to an ArrayList, but if you’re going to process them in any meaningful way, it helps to have common properties. The best way to do that is to derive them from the same base class.

So, those items are added now, and I need to create a subroutine that will list all the items to the console. I’ll call it ShowShoppingCart. It will accept the ArrayList as an argument.

Now, I need to create the ToString implementation. I’m simply going to create a for-each loop that iterates through each item and displays it to the console using the standard ToString implementation. I’ll use the Overrides keyword. That should do it.

Now, within the Main method I need to call ShowShoppingCart and pass it the Items array. I’m going to call Console.ReadKey so the console doesn’t disappear.

I’ll run it. You can see it displayed the items in the Items array in the order in which I put them in. Now, it’s common to want to sort them in different ways. For example, you might want to sort them by the title or by the price. First, we’ll handle sorting by the title.

To create a default sorter, you want to implement the IComparable interface. To do that, we’ll add Implements IComparable here. Then, we will implement the CompareTo function. All the Compare function wants is to know which of two items should come first in the sequence. So, it’s going to pass us an instance of the other object. In other words, this is running within an instance of one of our objects, and it’s going to pass us, as the object parameter, the object that we need to compare our own instance to. We then need to return the one that comes first in the sequence.

It’s actually really easy. All I’m going to do is to call the base class’ CompareTo method. I’m going to sort it by Title by default. I’m going to refer to the Title property and call the CompareTo method. Then, I’m going to pass it the object that it sent me, cast properly.

Now I need to call the Items.Sort method in the Main routine to actually perform the sort. I’m not going to pass it any parameters because I want it to perform a default sort.

So let’s run this and see if it sorted properly. You can see that it did indeed sort it by title: Contoso, Fabrikam, then Windows 7, and then Windows Vista. Now, what if you wanted to sort it by price instead? You can only have the one default sort order.

There are a couple of different ways you can go about sorting it in different ways. The most straightforward way is to create a custom IComparer implementation. Now, IComparable was an interface that we derived our class from. IComparer is actually a class in and of itself.

I’ll call it SortItemByPrice. We’ll implement the IComparer interface. You can see VisualBasic creates a basic implementation for me here. All I’m going to do now is to cast the two items to their correct classes, because they’re both passed to me as base objects. Then, I’m going to call the base CompareTo method and allow the CompareTo method to sort it out, because the .NET Framework developers have already done that work for me.

So, here you can see I’m going to call the CompareTo method of the Price property for the first object and then simply pass it the second item. We’ll run this again—it’ll sort in the same order because I didn’t actually create an instance of the SortItemsByPrice class yet.

We’ll call this instance PriceSort As IComparer. So, you can see I’m creating an instance of the SortItemByPrice class. Now, to the Item.Sort method, I will pass my instance.

Run this one more time, and you can see the ArrayList.Sort method used my IComparer instance to compare each of the objects in the array to determine the sort order based on that instance of SortItemByPrice, sorting them by the price attribute from least to greatest. So, the smallest price started the list, and the larger price ended the list.

That’s a pretty thorough demonstration of the ArrayList class. There are a couple of other collections that are useful. The first of those is Queue. Queue is a first-in, first-out type collection. You would use it for customers waiting in line. The first person who shows up should be the first person served. You don’t generally sort Queues, instead you add items to them (you Enqueue them) or you remove items from the array (you Dequeue them). I’m simply going to replace the ArrayList instance here with an instance of Queue.

Again, you don’t call the Add method, you call the Enqueue method. I no longer need to sort it, because you don’t generally sort queues. And, we’re going to need to update the ShowShoppingCart method to work with the Queue instead. You shouldn’t iterate through a Queue with a for-each loop. Instead, what you’re going to do is to Dequeue each object in sequence. To do that, I’ll create a While loop that continues as long as there is at least one item in the Queue.

Notice that for every Item I have to cast it to the correct type because Queue takes an Object, and it returns an Object. I can’t do what I need to do with an Object, however, and that requires casting. Later, you’ll learn how to use generics, which allow you to use classes like Queue and Stack in a strongly-typed way. So, I’ll run this now and what we should see is the Items displayed in exactly the order that I added them in. That’s what we expect, because it’s a first-in, first-out type collection.

You’ll see a different behavior from the Stack collection. If you’re a developer who has done low-level work, then you’ll probably be familiar with how stacks work. Stacks work in a first-in, last-out configuration. So, it’s common to use in the development environment because of the way methods pass arguments back to the calling method. So, MethodA calls MethodB, and then MethodB calls MethodC, the operating system needs to know where to return execution to when MethodC ends. It goes to the last caller, not the first caller. So, after MethodC ends, execution returns to MethodB. After MethodB ends, execution returns to MethodA. Last-in, first-out.

I’ll change this to a Stack, and instead of calling Enqueue, you Push them onto the stack. I need to update the ShowShoppingCart implementation. Instead of calling Dequeue, you call Pop—you Pop objects off the stack. If you wanted to read an object without removing it, you would call Peek. Now, you’ll notice that the items are in the exact opposite order that I added them to the array.

Return to the .NET Framework Fundamentals Tutorials Table of Contents.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>