I'm going to hazard a guess that your statement that the code is "slightly modified to work" means that this code:
newlistitem.Value = options[j][valuefield].ToString() +
((options[j]["pdprice"].ToString().Length > 0 ) ?
"/" + options[j]["pdprice"].ToString() : "" );
actually looked like this:
newlistitem.Value = options[j][valuefield].ToString() +
options[j]["pdprice"].ToString().Length > 0 ?
"/" + options[j]["pdprice"].ToString() : "";
(note the missing parenthesis)
The reason that this code will produce this error is that due to operator precedence, what will get evaluated is this:
String a = options[j][valuefield].ToString();
Int32 b = options[j]["pdprice"].ToString().Length;
String c = a + b;
Boolean d = c > 0;
String e = "/" + options[j]["pdprice"].ToString();
String f = "";
newlistitem.value = d ? e : f;
With this way of looking at it, a+b
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".
By adding the parenthesis, your "slight modification", you've essentially rewritten the code to do this:
String a = options[j][valuefield].ToString();
String b = options[j]["pdprice"].ToString().Length;
Boolean c = b > 0; <-- this is different
String d = "/" + options[j]["pdprice"].ToString();
String e = "";
String f = c ? d : e;
String g = a + f; <-- and this
newlistitem.value = g;
Notice the difference between d
in the first code and c
in the second code. You've moved the concatenation of the string out where it belongs, together with the other strings.
So your slight modification works since it is the correct way of doing it, if you want to keep those expressions.
The accepted answer is a much better alternative. My goal was to give you an explanation as to the reason of the exception.