Is there an IDictionary implementation that, on missing key, returns the default value instead of throwing?

前端 未结 15 1825
暗喜
暗喜 2020-11-27 04:00

The indexer into Dictionary throws an exception if the key is missing. Is there an implementation of IDictionary that instead will return de

15条回答
  •  时光取名叫无心
    2020-11-27 04:49

    This question helped to confirm that the TryGetValue plays the FirstOrDefault role here.

    One interesting C# 7 feature I would like to mention is the out variables feature, and if you add the null-conditional operator from C# 6 to the equation your code could be much more simple with no need of extra extension methods.

    var dic = new Dictionary();
    dic.TryGetValue("Test", out var item);
    item?.DoSomething();
    

    The downside of this is that you can't do everything inline like this;

    dic.TryGetValue("Test", out var item)?.DoSomething();
    

    If we'd need/want to do this we should code one extension method like Jon's.

提交回复
热议问题