Dmitrij Holkin
Dmitrij Holkin

Reputation: 2055

Dictionary objects function Exists adding not existing key to dictionary

Sub test()
    Dim authDict As Dictionary
    Set authDict = CreateObject("Scripting.Dictionary")

    authDict.Add "Anton", 1
    authDict.Add "Martin", "3"
    authDict.Add "Dave", 1

    testKey = authDict.Exists("Alina") ' False, but adding this Key to dictionary by itself
    testVal = authDict("Alina")
    testKey2 = authDict.Exists("Alina") ' now it true
    testVal2 = authDict("Alina")
End Sub

Why after not exists state dictionary adding this key to dictionary by themselves? How to prevent this

Upvotes: 3

Views: 110

Answers (1)

Pᴇʜ
Pᴇʜ

Reputation: 57683

The issue here is that this line

testVal = authDict("Alina")

will add the item Alina to the dictionary. So you should only run it if it already exists, otherwise it will be created. Use the Exists() method for this like below:

If authDict.Exists("Alina") Then ' False, but adding this Key to dictionary by itself
    testVal = authDict("Alina")
Else
    MsgBox "Alina does not exist"
End If

Why?

By using authDict("Alina") you use the Item property of the Dictionary object submitting Alina as parameter key.

So according to the documentation the item property "Sets or returns an item for a specified key in a Dictionary object.". Since Alina doesn't exist yet there is nothing to return, so it sets it by default.

The documentation of the item property furthermore says:

If key is not found when changing an item, a new key is created with the specified newitem. If key is not found when attempting to return an existing item, a new key is created and its corresponding item is left empty.

Source: Item property section Remarks.

Upvotes: 4

Related Questions