cchampion
cchampion

Reputation: 7921

Compiler error using C# conditional operator

I can't seem to find what I need on google, and bet I'll get quick answer here.

    String str;
    bool b = true;
    b ? str="true" : str="false";

    Console.Out.WriteLine(str);

that ? : syntax looks correct to me. I'm getting compiler error though.

Program.cs(13,28):
error CS1002: ; expected
Program.cs(13,28):
error CS1525: Invalid expression term ':'
Program.cs(13,30):
error CS1002: ; expected

Not sure about the csharp syntax, but that builds in cpp. Please help! thanks!

UPDATE: About 10 of you give the correct answer LOL, so I'll just award to the first person who submitted it.

interesting Syntax, and I think I actually like it better than c++ syntax.

The actual code I was doing this for is:

ftp.ConnectMode = job.FTPUsePassiveMode ? FTPConnectMode.PASV : FTPConnectMode.ACTIVE;

Upvotes: 7

Views: 1619

Answers (7)

Kent Boogaart
Kent Boogaart

Reputation: 178630

str = b ? "true" : "false";

But you could just do this:

str = b.ToString();

Or even cut out the middleman altogether:

Console.WriteLine(b);

Upvotes: 15

Jeff Yates
Jeff Yates

Reputation: 62377

Your code should read:

str = b ? "true" : "false";

However, this is akin to just calling b.ToString().ToLower(). That said, I suspect your actual use-case is a little more complex than just converting the Boolean value to a string.

Update
As indicated in the comments, the conditional operator returns a value; it is not for control flow like if/else.

Upvotes: 15

jrista
jrista

Reputation: 32950

Just out of curiosity, why not just do this:

bool b = true;
string str = b.ToString();

In .NET, value types automatically convert their value to a string when .ToString() is called...including booleans.

Upvotes: -1

Ben Voigt
Ben Voigt

Reputation: 283614

The ternary operator can't be the top-level of a statement in C#, because C# requires that top-level expressions have a side-effect.

Upvotes: 0

Yoopergeek
Yoopergeek

Reputation: 5642

What everyone else said, and: http://msdn.microsoft.com/en-us/library/ty67wk28.aspx

Upvotes: 2

Adam Robinson
Adam Robinson

Reputation: 185593

The ternary operator doesn't allow for statement switching, only value switching. You want to do this:

str= b ? "true" : "false"

(obviously b.ToString()) is a better solution for this particular problem, but I'm assuming this is just an example).

Upvotes: 4

RC.
RC.

Reputation: 28197

str = (b) ? "true" : "false";

Upvotes: 1

Related Questions