Friday, October 13, 2006

Dictionaries and null keys

C# does not let you initialize a dictionary entry by simply assigning a value to a non-existant key in the dictionary. So instead of
  mydictionary[key] = value;    
...where "key" does not yet exist in the dictionary, it is necessary to do something like this...
  if (mydictionary.ContainsKey(key))
  {
    mydictionary[key] += value;
    //or
    mydictionary[key] = value;
  }
  else
  {
    mydictionary.Add(key, value);
  }

No comments:

Post a Comment