Encountered Another Exception : "Value does not fall within the expected range."

Posted by Eklavya Mirani on August 27, 2012

Today while debugging my new Windows Phone 7 Application, I encountered an exception I had never seen before:
"Value does not fall within the expected range."
To be precise, I encountered it here:

SomeRandomDictionary["TheMightyKey"]="WeirdValue";

I scratched my head, puzzled, cuz I knew this statement had executed before successfully. And then after some googling, I came to know this happens if you assign a Key value pair for some key that already exists in the dictionary.

You must be wondering why I am telling you this story, and why the heck am I not posting the solution, the answer is simple:

It makes me feel like The Wise One. AND its my blog, I can do whatever I want ;)

Anyway, coming to the solution, you can simply resolve this by checking if a key already exists and removing it if it does before assigning a new KeyValuePair.

if(SomeRandomDictionary.Contains("TheMightyKey"))

SomeRandomDictionary.Remove("TheMightyKey");

SomerandomDictionary["TheMightyKey"]="Weird Value";

There you go, now you probably wont ever see this exception again.

Happy Coding.