16

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

Saokat Ali
  • 1,055
  • 2
  • 12
  • 18

5 Answers5

29

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."

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • This doesn't really address the reason for the design decision; they could just have easily made it return `default(DateTime)` instead of null. – Extragorey Jan 17 '18 at 01:49
  • @Extragorey Yes it does, in particular the final sentence: whatever the "not found" value is, you may need to store that value as meaningful. If fetching a key that isn't found returns `default(DateTime)` then you can't distinguish between "value is `default(DateTime)`" and "key isn't present," at least without an additional call to `ContainsKey()` (which would unnecessarily double the cost of the operation). For a dictionary containing a reference type as the value, maybe `null` is a meaningful state apart from "key isn't present." – cdhowie Jan 17 '18 at 02:02
  • Thanks, that explanation makes more sense. – Extragorey Jan 18 '18 at 03:00
5

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

object myvalue = dict.ContainsKey(mykey) ? dict[mykey] : null;
BeemerGuy
  • 8,139
  • 2
  • 35
  • 46
5

Try using

Dictionary.TryGetValue Method

or maybe

Dictionary.ContainsKey Method

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
4

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.

Jay Riggs
  • 53,046
  • 9
  • 139
  • 151