Tag: dictionary object

The Dictionary Object: similar to PHP arrays.

Posted by – July 25, 2007

In a previous post entitled Associative Arrays in VB.NET I spoke of using a Collection Object to achieve similar functionality to associative arrays in PHP. Upon further inspection, I feel that the System.Collections.Generic.Dictionary Object (hereafter written as Dictionary Object) is a closer match.

The reason I initially chose to write about the Collection Object is because the Dictionary Object requires all keys to be of the same type, and all values to be of the same type. Of course .NET (both VB.NET and CSharp.NET) is a strongly typed language, whereas PHP is not.

The main advantage a Dictionary has over a regular Collection, is that you can edit items. It also provides a syntax to add items which is similar to that of PHP.

The first step is to add the System.Collections.Generic library to your file, with the following directive:


using System.Collections.Generic;


imports System.Collections.Generic

Then you can declare the Dictionary Object:

        Dictionary dict = new Dictionary();
        dict["one"] = "First Item";
        dict["two"] = "Second Item";
        dict["one"] = "Look, I just edited the first Item!";


        Dim dict As Dictionary(Of String, String) = New Dictionary(Of String, String)
        dict("one") = "First Item"
        dict("two") = "Second Item"
        dict("one") = "Look, I just edited the first Item!"

Look at that! Aside from the missing dollar sign in front of variables, this looks like PHP!