Is there a more elegant way of adding an item to a Dictionary<> safely?

后端 未结 5 782
梦如初夏
梦如初夏 2020-12-13 16:37

I need to add key/object pairs to a dictionary, but I of course need to first check if the key already exists otherwise I get a \"key already exists in dictionary

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 17:30

    As usual John Skeet gets in there with lighting speed with the right answer, but interestingly you could also have written your SafeAdd as an Extension Method on IDictionary.

    public static void SafeAdd(this IDictionary. dict, K key, T value)...
    

提交回复
热议问题