Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 823
cchampion Avatar asked Mar 02 '10 19:03

cchampion


2 Answers

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.

like image 136
Jeff Yates Avatar answered Sep 28 '22 10:09

Jeff Yates


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

But you could just do this:

str = b.ToString();

Or even cut out the middleman altogether:

Console.WriteLine(b);
like image 34
Kent Boogaart Avatar answered Sep 28 '22 10:09

Kent Boogaart