Using ternary operator on Console.WriteLine

亡梦爱人 提交于 2019-12-08 02:25:51

问题


I need to print some string based on the true or false of a condition.

For example:

if(i == m) {
Console.WriteLine("Number is valid");
} else {
Console.WriteLine("Number is invalid");
}

How can I check this condition and print a message using conditional operator and with only one Console.WriteLine?

I was trying:

(i == m) ? Console.WriteLine("Number is valid") : Console.WriteLine("Number is not valid");

I know I'm doing it wrong here. Can someone please tell me the correct way?


回答1:


Try this:

Console.WriteLine("Number is " + ((i == m) ? "valid" : "not valid"));



回答2:


Move your ternary operation inside WriteLine

Console.WriteLine((i == m) ? "Number is valid" : "Number is not valid");



回答3:


The conditional operator is an operator. It returns a value. The value it returns is the value from one of its branches.

Console.WriteLine is a void method. It does not return a value. As a result, you cannot use it as one of the branches of the conditional operator.

BTW, this operator is correctly called "the conditional operator". It happens to be a ternary operator, meaning that it is an operator which takes three parameters. ere It runs:

  1. Unary
  2. Binary
  3. Ternary
  4. Quaternary

etc.

There happens to be only a single ternary operator in C# at present - the conditional operator. There happen to be no quaternary or higher-order operators.



来源:https://stackoverflow.com/questions/20258975/using-ternary-operator-on-console-writeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!