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:

CSharp.NET


using System.Collections.Generic;

VB.NET


imports System.Collections.Generic

Then you can declare the Dictionary Object:
CSharp.NET


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

VB.NET


<%
        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!

1 Comment on The Dictionary Object: similar to PHP arrays.

  1. [...] 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. [...]

Leave a Reply

Your email address will not be published. Required fields are marked *

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>