Just give me a null already
In C#, the Dictionary
is quite a staple. I use it quite a bit. However I've always been bothered by the fact that the indexer throws a KeyNotFoundException
exception rather than returning null:
Dictionary<int, string> MyValues = GetDictionary(); string aValue = MyValues[1]; // THROWS ERROR IF 1 DOESN'T EXIST
This required a lot of code that looks like:
Dictionary<int, string> MyValues = GetDictionary(); string aValue = null; if (MyValues.ContainsKey(1)) { aValue = MyValues[1]; }
Or perhaps the tertiary approach:
Dictionary<int, string> MyValues = GetDictionary(); string aValue = MyValues.ContainsKey(1) ? MyValues[1] : null;
To me this is code-bloat for the many cases when a null string is perfectly acceptable.
Introducing GetValueOrDefault
Finally, as of C# 7.1, a better solution is here. One I only recently discovered. It's very similar to the ever useful .FirstOrDefault()
call. It's GetValueOrDefault
. It even allows you to specify a default other than null. Here's it's use:
Dictionary<int, string> MyValues = GetDictionary(); // This returns null if not found string aValue = MyValues.GetValueOrDefault(1); // This returns "" if not found. A helpful alternative string bValue = MyValues.GetValueOrDefault(1, String.Empty);
Much nicer!
I just need to decide if it's worth replacing ALL my old ContainsKey's
...