c# - Dictionary throwing an Argument Exception even when protected by ContainsKey -


in production, code (c#, .net 4.5.1) throwing argumentexception stating an item same key has been added.

code:

public myclass() {    this.mycontent = new dictionary<string, string>();             }  public idictionary<string, string> mycontent { get; private set; }  public void addorupdatedictionary(string key, string value) {     if (this.mycontent.containskey(key))     {         this.mycontent[key] = string.concat(this.mycontent[key], value);     }     else     {         this.mycontent.add(key, value);     } } 

however, can't recreate error in unit test. e.g. behaves expected -

[testmethod] public void addorupdatedictionary_whenaddingsecondvalue_valueisappended() {     const string inputvalue1 = "value1";     const string inputvalue2 = "value2";     string expectedvalue = string.concat(inputvalue1, inputvalue2);      var obj = new myclass();     obj.addorupdatedictionary("key", inputvalue1);     obj.addorupdatedictionary("key", inputvalue2);      assert.areequal(expectedvalue, obj.mycontent["key"]); } 

what causing this? thought containskey would've made code safe.

is weird threading gotcha i've missed? code on model in mvc site, no instances of static.

assuming problem thread related , allowed change type of dictionary, use concurrentdictionary. exposes method (addorupdate) can what's intended: either add value or refactor value based on present value:

    class myclass     {         public myclass()         {             this.content = new concurrentdictionary<string, string>();         }          concurrentdictionary<string, string> content;         public idictionary<string, string> mycontent { { return content; } }          public void addorupdatedictionary(string key, string value)         {             content.addorupdate(key, value, (k, contentvalue) => string.concat(contentvalue, value));            }     } 

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -