Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm going to hazard a guess that your statement that the code is "slightly modified to work" means that this code:</p> <pre><code>newlistitem.Value = options[j][valuefield].ToString() + ((options[j]["pdprice"].ToString().Length &gt; 0 ) ? "/" + options[j]["pdprice"].ToString() : "" ); </code></pre> <p>actually looked like this:</p> <pre><code>newlistitem.Value = options[j][valuefield].ToString() + options[j]["pdprice"].ToString().Length &gt; 0 ? "/" + options[j]["pdprice"].ToString() : ""; </code></pre> <p>(note the missing parenthesis)</p> <p>The reason that <em>this</em> code will produce this error is that due to operator precedence, what will get evaluated is this:</p> <pre><code>String a = options[j][valuefield].ToString(); Int32 b = options[j]["pdprice"].ToString().Length; String c = a + b; Boolean d = c &gt; 0; String e = "/" + options[j]["pdprice"].ToString(); String f = ""; newlistitem.value = d ? e : f; </code></pre> <p>With this way of looking at it, <code>a+b</code> will produce a new string, since adding something to a string will convert that something to a string for concatenation. Basically, "xyz" + 3 gives "xyz3".</p> <p>By adding the parenthesis, your "slight modification", you've essentially rewritten the code to do this:</p> <pre><code>String a = options[j][valuefield].ToString(); String b = options[j]["pdprice"].ToString().Length; Boolean c = b &gt; 0; &lt;-- this is different String d = "/" + options[j]["pdprice"].ToString(); String e = ""; String f = c ? d : e; String g = a + f; &lt;-- and this newlistitem.value = g; </code></pre> <p>Notice the difference between <code>d</code> in the first code and <code>c</code> in the second code. You've moved the concatenation of the string out where it belongs, together with the other strings.</p> <p>So your slight modification works since it is the correct way of doing it, <strong>if you want to keep those expressions</strong>.</p> <p><a href="https://stackoverflow.com/questions/1651490/in-c-checking-string-length-greater-than-zero-produces-error/1651509#1651509">The accepted answer</a> is a much better alternative. My goal was to give you an explanation as to the reason of the exception.</p>
 

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