Why does the following Conditional operator work weirdly in a StringBuilder containing a Nullable type? in c #?

StringBuilder htmlResp=new StringBuilder(); int? cuID= 1; string cuName="Tom"; string cuEmpID="ZXCV"; htmlResp .Append( "<option value=\"" + cuID.Value + "\">" + cuName+" ("+cuEmpID==""? "-":cuEmpID+")"+ "</option>"); html.Resp.ToString(); 

I can’t understand why the above code (modified from real codes) always gives me a strange result: "ZXCV" instead of "Tom (ZXCV)".

Does anyone know the reason and can provide a link if possible?

+6
source share
2 answers

You are missing parentheses around a conditional expression.

Try this instead:

 string text = "<option value=\"" + cuID.Value + "\">" + cuName + " (" + (cuEmpID == "" ? "-" : cuEmpID) + ")" + "</option>"; htmlResp.Append(text); 

As for why the missing parentheses caused this ... What an interesting question!

To answer this, let me simplify the source code a bit:

 string text = ">>>" + cuEmpID == "" ? "-" : cuEmpID + "<<<"; // Gives "ZXCV<<<" 

What happens because the conditional expression uses ">>>" + cuEmpID == "" as a condition. This is not equal to "", so the right side of the conditional expression is used, namely the cuEmpID + "<<<" , which gives the result that we see.

You really have to simplify the expression, for example:

 string normalisedEmpID = cuEmpID == "" ? "-" : cuEmpID; string text = string.Format ( "<option value=\"{0}\">{1} ({2})</option>", cuID.Value, cuName, normalisedEmpID ); 
+5
source

A good example is "not too hard to express."

  "<option value=\"" + cuID.Value + "\">" + cuName + " ("+cuEmpID==""? "-":cuEmpID+")"+ "</option>"); 

compiled as

  ("<option value=\"" + cuID.Value + "\">" + cuName+" ("+cuEmpID ) == "" ? "-" : cuEmpID+")"+ "</option>"); 

A simple β€œfix” would be

  "<option value=\"" + cuID.Value + "\">" + cuName + " (" + ((cuEmpID == "") ? "-" : cuEmpID ) + ")" + "</option>" 

but for readability, use some intermediate variables. ?: should never be nested in other expressions.

+3
source

All Articles