Please see my code:
IDictionary dictionary = new Hashtable();
const string key = "key";
const string value = "value";
dictionary[key] = null; // set some trigger here
// set value
IDictionaryEnumerator dictionaryEnumerator = dictionary.GetEnumerator();
while (dictionaryEnumerator.MoveNext())
{
DictionaryEntry entry = dictionaryEnumerator.Entry;
if (entry.Value == null) // some business logic check; check for null value here
{
entry.Value = value; // set new value here
break;
}
}
Assert.AreEqual(value, dictionary[key]); // I have Fail here!
I wonder :
-
What is correct approach for set new value for IDictionary when
I do not know the corresponding key. -
Why my example is not working? As I understand I have set new value
for DictionaryEntry by value (and value here is a reference) but
it was not affected in source IDictionary. Why?
DictionaryEntry does not hold a direct reference to the actual values, the internal datastructure is quite different. Therefore, setting the value on a DictionaryEntry will do nothing to the values actually in the Hashtable.
To set a value, you must use the indexer. You can enumerate on the keys rather on the key-value pairs. This code is equivalent of what you tried with DictionaryEntry: