views:

200

answers:

7

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)" : "");
+8  A: 

Add parentheses:

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

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.

Scott Muc
A: 

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.

Matthew Brubaker
+4  A: 

What about this?

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

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)");
Sergio
+3  A: 

Extra parenthesis or even nicer use AppendFormat

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

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#.

orip