C# conditional operator error Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

我怕爱的太早我们不能终老 提交于 2019-11-29 14:05:08

The conditional operator is an expression, not a statement, that means it cannot stand alone, as the result has to be used somehow. In your code, you don't use the result, but try to produce side effects instead.

Depending on the condition before the ? the operator returns the result of either the first or the second expression. But Console.WriteLine()'s return type is void. So the operator has nothing to return. void is not a valid return type for the ?: operator. So a void-method cannot be used here.

So you could do something like that:

while (n-- > 0) {
    int num = Int32.Parse(Console.ReadLine());
    string result = checkPrime(num) ? "Prime" : "Not Prime";
    Console.WriteLine(result);
}

or you use the operator inside the Console.WriteLine() call:

while (n-- > 0) {
    int num = Int32.Parse(Console.ReadLine());
    Console.WriteLine(checkPrime(num) ? "Prime" : "Not Prime");
}

In both examples, the operator returns one of the two strings depending on the condition. That's what this operator is for.


Note that you do not need to compare the result of checkPrime() to true. The result already is a bool.

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