开发者

Compiler error using C# conditional operator

开发者 https://www.devze.com 2022-12-22 03:49 出处:网络
I can\'t seem to find what I need on google, and bet I\'ll get quick answer here. String str; bool b = true;

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 Sy开发者_如何学Cntax, 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);


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


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


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号