Note that there are some explanatory texts on larger screens.

plurals
  1. PO+ string concat operator with a null operand
    primarykey
    data
    text
    <p>A co-worker showed me a very strange behavior and I'd like to know if someone could explain me why.</p> <p>A basic constructor with 2 string params:</p> <pre><code> public MyClass(string str1, string str2) { this.s1 = str1; this.s2 = str2; this.s3 = Method(str2 + "._className", str1); } </code></pre> <p>Method is:</p> <pre><code>public string Method(string key, string defaultValue) { List&lt;string&gt; list = _vars[key]; if (list == null) return defaultValue; string res = ""; foreach (string s in list) { if (res != "") res += ","; res += s; } return res; } </code></pre> <p>When this ctor is called within an aspx page with <code>str2</code> as <code>null</code>, all works fine because if an operand of string concatenation <code>+</code> is <code>null</code>, an empty string is substituted.</p> <p>But when this ctor is called with <code>str2</code> as <code>null</code> in a background thread, a <code>NullReferenceException</code> is fired.</p> <p>The problem was solved by testing <code>str2 != null</code> before using it, but I'd really like to know why the same code sometimes fires an exception, sometimes not!</p> <p>Here is the stack trace:</p> <pre><code>Exception: System.NullReferenceException Message: Object reference not set to an instance of an object. StackTrace: at MyClass..ctor(String str1, String str2) at AbandonedCartsNotificationJob.NotifyAbandonedCarts() in AbandonedCartsNotificationJobPartial.cs:line 39 at AbandonedCartsNotificationJob.work() in AbandonedCartsNotificationJob.cs:line 15 at MyRuntime.JobManager.run() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload