1

I'm using a string builder to build some SQL Scripts. I have a few Boolean Properties that I would like to test and then output different text based on true/false. I've you the C# syntax below when assigning a value to a variable, but it isn't working for this particular situation. Any ideas?

What I'm used to doing:

string someText = (dbInfo.IsIdentity) ? "First Option" : "Second Option";

Trying to duplicate the same thing inside a StringBuilder method, but this isn't working..

script.Append("sometext" + (dbInfo.IsIdentity) ? " IDENTITY(1,1)" : "");

7 Answers 7

8

Add parentheses:

script.Append("sometext" + ((dbInfo.IsIdentity) ? " IDENTITY(1,1)" : ""));
Sign up to request clarification or add additional context in comments.

Comments

4

What about this?

script.Append( "sometext" );
script.Append( dbInfo.IsIdentity ? " IDENTITY(1,1)" : "" );

Comments

3

Extra parenthesis or even nicer use AppendFormat

script.AppendFormat("sometext{0}", dbInfo.IsIdentity ? " IDENTITY(1,1)" : "");

Comments

3

Other from stating that if you have a stringbuilder you should use it to concatenate strings.

That said, the code bellow should work.

script.Append("sometext");
script.Append(dbInfo.IsIdentity ? " IDENTITY(1,1)" : "");

In this particular case you could also do:

script.Append("sometext");
if(dbInfo.IsIdentity) script.Append(" IDENTITY(1,1)");

Comments

2

Just a hunch but I think you need some more brackets:

script.Append("sometext" + ((dbInfo.IsIdentity) ? " IDENTITY(1,1)" : ""));

I would urge you to use a temporary variable for readability sake.

Comments

0

First, I would try wrapping the if/then/else in a set of parenthesis and see if that fixes the problem. It may be a problem with the order in which that expression is being evaluated.

Comments

0

A quick suggestion: if you're generating SQL like this, you may have a better time using a templating like StringTemplate to generate it vs. using straight C#.

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.