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;
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
.
str = b ? "true" : "false";
But you could just do this:
str = b.ToString();
Or even cut out the middleman altogether:
Console.WriteLine(b);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With