Pages

Wednesday, July 6, 2011

Be sure to consider case when creating Dictionary keys (VBScript 4.0)

The Dictionary object is a member of the Microsoft Scripting Runtime Library. The simple definition of a Dictionary object is an array of key/item pairs. However, you should keep in mind that the Key values you use to create the Dictionary object are case-sensitive. This is especially important to remember when you're using non-numeric key values.

For example, the following lines of code produce a Dictionary object with two elements:

Dim myDict
Set myDict = CreateObject("Scripting.Dictionary")

myDict.Add "SMD", 1
myDict.Add "smd", 2

The object has two keys because it considers "smd" and "SMD" to be different key values. To avoid this problem, consider using the UCase() or Lcase() functions when storing and referencing alphanumeric key values.

Another option is to set the CompareMode property to Text Compare before adding any items to the Dictionary, like so:

myDict.CompareMode = 1 'TextCompare

If you do this, then adding values to the Dictionary that differ only in case will produce a duplicate key error.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.