Tag: vb

Associative Arrays in VB.NET

Posted by – July 5, 2007

I am a PHP programmer at heart (by that I mean it is what I know best). However I program in .NET for work (its hard to find php jobs). As such, I often find myself wanting to solve quick tasks with an associative array. Unfortunately, they don’t really exist in .net.

What I usually end up doing is create a Collection instead. A Collection allows you to add any object as an item, and you can also assign a String as a key to it. So for example, if I wanted to create a collection of my family, I could do something like:


dim myFamily as Collection = new Collection
myFamily.add("Leah","wife")
myFamily.add("Cal","father")

This is similar to a php associative array, but note that the first argument is the information, or Object, itself. The second argument is the key. In this case I am simply using strings for the Object, but I could have put anything there.

Now that I have my “Associative Array”, which is actually a Collection, I can lookup values like so:


If myFamily.Contains("dad") Then
Response.Write("My father is: " & myFamily("father").ToString)
End If

The downside to a collection is that you cannot edit items in a collection. A workaround is to delete the item, then create a new one with a same key. However, collections really seem to be meant more for static information you don’t want to change. If you are looking to change the items, check out my article The Dictionary Object: similar to PHP arrays.