It really annoys me that I must use .ContainsKey
instead of just doing a value==null
in a dictionary. Real life example:
var dictionary = new Dictionary<string, FooBar>();
var key = "doesnt exist";
var tmp = dictionary[key] ?? new FooBar(x, y);
Instead, I have these choices:
var key = "doesnt exist";
FooBar tmp = null;
if (dictionary.ContainsKey(key))
{
tmp = dictionary[key];
} else {
tmp = new FooBar(x, y);
}
Or this:
FooBar tmp = null;
if (!Dictionary.TryGetValue(key, out tmp))
{
tmp = new FooBar(x, y);
}
To me, this code is extremely verbose. Is there a built-in generic class which implements IDictionary (or otherwise allows key-value type access) but doesn't throw an exception when I try to lookup a key, and instead return null?