c# - + string concat operator with a null operand -


a co-worker showed me strange behavior , i'd know if explain me why.

a basic constructor 2 string params:

    public myclass(string str1, string str2)     {         this.s1 = str1;         this.s2 = str2;         this.s3 = method(str2 + "._classname", str1);     } 

method is:

public string method(string key, string defaultvalue) {     list<string> list = _vars[key];     if (list == null) return defaultvalue;     string res = "";     foreach (string s in list)     {         if (res != "") res += ",";         res += s;     }     return res; } 

when ctor called within aspx page str2 null, works fine because if operand of string concatenation + null, empty string substituted.

but when ctor called str2 null in background thread, nullreferenceexception fired.

the problem solved testing str2 != null before using it, i'd know why same code fires exception, not!

here stack trace:

exception: system.nullreferenceexception  message: object reference not set instance of object. stacktrace:  @ myclass..ctor(string str1, string str2)  @ abandonedcartsnotificationjob.notifyabandonedcarts() in abandonedcartsnotificationjobpartial.cs:line 39  @ abandonedcartsnotificationjob.work() in abandonedcartsnotificationjob.cs:line 15  @ myruntime.jobmanager.run()  @ system.threading.threadhelper.threadstart_context(object state)  @ system.threading.executioncontext.runtrycode(object userdata)  @ system.runtime.compilerservices.runtimehelpers.executecodewithguaranteedcleanup(trycode code, cleanupcode backoutcode, object userdata)  @ system.threading.executioncontext.runinternal(executioncontext executioncontext, contextcallback callback, object state)  @ system.threading.executioncontext.run(executioncontext executioncontext, contextcallback callback, object state)  @ system.threading.threadhelper.threadstart() 

there obscure bug in .net framework's implementation of string concatenation, affected concatenations of 4 objects, 1 of objects non-null and provided override of tostring returned null. situation isn't case here.

this situation caused 1 of following:

  • _vars null when method called
  • due misuse of _vars in multi-threaded application, internal state of _vars has been corrupted, resulting in nullreferenceexception when operator [] used.

Comments

Popular posts from this blog

php - get table cell data from and place a copy in another table -

javascript - Mootools wait with Fx.Morph start -

php - Navigate throught databse rows -