+ string operator concat with null operand

The employee showed me very strange behavior, and I would like to know if anyone can explain to me why.

Basic constructor with 2 string parameters:

public MyClass(string str1, string str2) { this.s1 = str1; this.s2 = str2; this.s3 = Method(str2 + "._className", str1); } 

Method:

 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 this ctor is called on an aspx page with str2 as null , everything works fine, because if the string concatenation operand + is null , the empty string is replaced.

But when this ctor is called with str2 as null in the background thread, a NullReferenceException .

The problem was solved by testing str2 != null before using it, but I would really like to know why the same code sometimes throws an exception, sometimes not!

Here is the stack trace:

 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() 
+8
c #
source share
2 answers

In the implementation of the .NET Framework, a fuzzy error related to string concatenation was implemented, but it affected only concatenation of 4 objects, where one of the objects was not null and provided a ToString override that returned null. It is clear that the situation here is not so.

This situation is most likely caused by one of the following:

  • _vars is null when Method is called
  • Due to improper use of _vars in a multithreaded application, the internal state of _vars corrupted, resulting in a NullReferenceException when the [] operator is used.
+4
source share

The problem is the implementation of the Method object. Since the implementation of + Operator interprets an empty value as an empty string . The null value of actull never enters the constructor when set to str2 . On the contrary, str1 directly enters a null value, and may, depending on the implementation, raise a null reference exception.

+3
source share

All Articles