2

How do I use a conditional operator inside a string?

Why is the value of this string missing TO_DATE( and ' the single quote? and what can I do to fix it?

StringBuilder sb = new StringBuilder();
//code...
sb.AppendLine("     '" + txtStatus.Text + "',");
sb.AppendLine("     TO_DATE(" + dtpEligDate.Value.ToString("yyyyMMddHHmmss") == "" ? "null" : dtpEligDate.Value.ToString() + "),");
sb.AppendLine("     '" + txtCoverageEndReason.Text == "" ? "null" : txtCoverageEndReason.Text + "',");
//code...

String value:

'',
7/19/2013 9:04:35 AM),
',

My understanding is that this is NOT caused by lack of escaping charecters, but because of the use of a conditional operator.

Thanks for the help!

1 Answer 1

6

It's because of operator precedence, add () to your ternary operator and it will work:

sb.AppendLine("TO_DATE(" + 
    (dtpEligDate.Value.ToString("yyyyMMddHHmmss") == "" ? "null" : dtpEligDate.Value.ToString()) + 
"),");

Basicaly it will first concatenate strings (+) and then evaluate conditional statement (?:), but you expect it to be opposite. Parentheses will fix it.

As a side note: it'd be better to use parametrized queries.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.