Previous | Index | Next 

[PRB] The Scripting.Dictionary object doesn’t work with Enum keys

Under VB6 enumerated values are nothing but aliases for 32-bit integer; conversely, under VB.NET an enumerated value is a first-class citizen. VB.NET languages allow implicit conversions between enumerated values and integers, therefore you usually don’t have to account for this minor difference, but there are a few exceptions, for example when you use an enum value as the key for a Scripting.Dictionary object:

Dim dict As New Dictionary

Sub Test(ByVal key As MyEnumType)
	Debug.Print dict(key) = dict(CInt(key))
End Sub

Under VB6 the Debug.Print statement displays True, whereas under VB.NET it display False; as you might guess, the reason is that – when used as keys for the dictionary – the enumerated value and its integer equivalent are considered as different values and therefore reference different dictionary elements.

We could easily modify the VB6Dictionary class to account for this minor difference, yet we decided not to, because it would add a major overhead each time any dictionary element is read or written to, and such overhead would be hardly justified given that it is a very rare case. (In many years only a single customer report this erratic behavior.)

As a result, if you use enumerated values as keys for a Dictionary object, ensure that you use them in a consistent way. In other words, you should either always use enumerated values or their corresponding integer values, but you should never mix them in the same project.


Previous | Index | Next