C# conditional operator error Only assignment, cal

2019-01-28 01:29发布

问题:

Hi I was writing a basic program to find if the input number is prime or not. I have a checkPrime(num) function that checks for prime number and returns true if num is prime else returns false. Now in my main() function I used conditional operator to shorten the code but I am getting an error which I am not sure about. Below is my code :

static void Main(String[] args) {
    int n = Int32.Parse(Console.ReadLine());
    while (n-- > 0) {
        int num = Int32.Parse(Console.ReadLine());
        (checkPrime(num) == true) ? Console.WriteLine("Prime") : Console.WriteLine("Not Prime");
    }
}

When I compile, I get the error as Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement in my while loop at conditional statement line. I am not sure what is it that I am missing. There is similar question here and people have answered that the conditional operator line is an expression and not a statement so there has to be some sort or assignment for the value of the expression. Same kind of example is given in MSDN reference where the explanation does something like this

// ?: conditional operator.
classify = (input > 0) ? "positive" : "negative";

But what I am not able to understand is in my function all I am trying to do is check the return value of the function and then print the output. So where does this expression thing comes in my case.

回答1:

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.