Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid key in Dictionary

Tags:

c#

collections

Why do dictionaries not just return null when an invalid key is used to index into the collection?

like image 599
Saokat Ali Avatar asked Dec 17 '10 06:12

Saokat Ali


People also ask

What does invalid key mean?

The INVALID KEY phrase is given control if an input or output error occurs because of a faulty index key. You can also include the INVALID KEY phrase in WRITE requests for QSAM files, but the phrase has limited meaning for QSAM files. It is used only if you try to write to a disk that is full.

Is an invalid key Python?

Python KeyErrorThis error means that you're trying to access an invalid key in a dictionary. This is typically because the key does not exist in the dictionary. In other words, there is no key/value pair corresponding to the key you used in the dictionary.

What happens if you try to access a dictionary with an invalid key?

A Python KeyError is raised when you try to access an invalid key in a dictionary. In simple terms, when you see a KeyError, it denotes that the key you were looking for could not be found. Here, dictionary prices is declared with the prices of three items.

What Cannot be a key in a dictionary?

These are things like integers, floats, strings, Booleans, functions. Even tuples can be a key. A dictionary or a list cannot be a key. Values, on the other hand, can literally be anything and they can be used more than once.


4 Answers

Because generic dictionaries could contain instances of a value type, and null is not valid for a value type. For example:

var dict = new Dictionary<string, DateTime>();
DateTime date = dict["foo"]; // What should happen here?  date cannot be null!

You should instead use the TryGetValue method of dictionary:

var dict = new Dictionary<string, DateTime>();
DateTime date;

if (dict.TryGetValue("foo", out date)) {
    // Key was present; date is set to the value in the dictionary.
} else {
    // Key was not present; date is set to its default value.
}

Also, a dictionary that stores reference types will still store null values. And your code might consider "value is null" to be different from "key does not exist."

like image 106
cdhowie Avatar answered Sep 25 '22 15:09

cdhowie


Microsoft decided that =)
Do an inline check to avoid that.

object myvalue = dict.ContainsKey(mykey) ? dict[mykey] : null;
like image 35
BeemerGuy Avatar answered Sep 26 '22 15:09

BeemerGuy


Try using

Dictionary.TryGetValue Method

or maybe

Dictionary.ContainsKey Method

like image 39
Adriaan Stander Avatar answered Sep 23 '22 15:09

Adriaan Stander


Practical reason: Because a Dictionary could store a null value. You wouldn't be able to differentiate this case with an exception, in your scenario.

like image 34
Jay Riggs Avatar answered Sep 23 '22 15:09

Jay Riggs