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


I have to add a key / object pair in a dictionary, but I have to first check whether the key already exists or not A " key exists in the dictionary " error The code below solves this, but it is condensed.

What is another great way to do this without doing string support methods?

  Using the system; Using System.Collections.Generic; Namespace TestDictStringObject {class program {static zero main (string [] args) {dictionary  not  before there being:  
  dictionary & lt; String, Object & gt; CurrentViews = New Dictionary & lt; String, Object & gt; (); Current view ["customer"] = "scene 1"; Current view ["Customer"] = "View 2"; Current view ["employee"] = "scene 1"; Current view ["report"] = "scene 1";  

Basically use add , if the existence of the key indicates a bug (so you want to throw it) and the indexor otherwise (this reference is the conversion There is a bit like the difference between casting and using as .)

If you are using C # 3 and you have the key There is a separate group of , you can also make it a nipper:

  var current view = new dictionary & lt; String, Object & gt; () {{"Customer", "View 2"}, {"Employee", "View 1"}, {"Report", "View 1"}}};  

This will not work in your case, although archive launchers always use add , which will throw on the second customer entry .


Comments

Popular posts from this blog

c# - ListView onScroll event -

PHP - get image from byte array -

Linux Terminal Problem with Non-Canonical Terminal I/O app -