I am using a dictionary to perform lookups for a program I am working on. I run a bunch of keys through the dictionary, and I expect some keys to not have a value. I catch the
Here is a one line solution (Keep in mind this makes the lookup twice. See below for the tryGetValue version of this which should be used in long-running loops.)
string value = dictionary.ContainsKey(key) ? dictionary[key] : "default";
Yet I find myself having to do this everytime I access a dictionary. I would prefer it return null so I can just write:
string value = dictionary[key] ?? "default";//this doesn't work