0

It's very convenient using inline sugar like that: obj?.func(); and obj ?? anotherObj

But I'm trying to find an alternative to the same approach in case I want to pull data from a dictionary without knowing whether the dictionary has the key I'm looking for or not.

Specifically I'd like to do something equivalent to:

someDictionary[someKey] ?? anotherValue such that, if key exists it would use the corresponding value in the dictionary and if not, it will use anotherValue. Obviously it's not possible to use as I wrote it here since it makes no sense, but the idea behind it is sound.

Is there a way to simplify it to be used inline, without making a separate check with if?

NewProger
  • 2,945
  • 9
  • 40
  • 58

1 Answers1

0

You can replace if checking with ternary operator

 var value = someDictionary.TryGetValue(someKey, out var val) ? val : anotherValue;

Anton
  • 801
  • 4
  • 10
  • This answer works, but with .NET Core 2+ and C# 7+, this has been implemented in CollectionExtensions. Basically @NewProger only needs to use `var value = someDictonary.GetValueOrDefault(someKey, anotherValue);` – Mark Cilia Vincenti Apr 11 '20 at 14:15
  • @MarkCiliaVincenti Thanks! I will remember it – Anton Apr 12 '20 at 12:06