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

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.

Leave a Comment