In Python, if I have a dict, and I want to get a value from a dict where the key might not be present I'd do something like:
lookupValue = somedict.get(someKey, someDefaultValue)
where, if someKey
is not present, then someDefaultValue
is returned.
In C#, there's TryGetValue()
which is kinda similar:
var lookupValue;
if(!somedict.TryGetValue(someKey, lookupValue))
lookupValue = someDefaultValue;
One gotcha with this though is that if someKey
is null
then an exception gets thrown, so you put in a null-check:
var lookupValue = someDefaultValue;
if (someKey != null && !somedict.TryGetValue(someKey, lookupValue))
lookupValue = someDefaultValue;
Which, TBH, is icky (3 lines for a dict lookup?) Is there a more concise (ie 1-line) way that is much like Python's get()
?