- Ähnliche Themen - Programm beenden
The ternary operator is an expression that cannot be used as a statement. In contrast, an assignment is an expression that can be promoted to a statement. (hence the error message referring to "assignment" expressions)
What you want is:
Here you are using the operator as an expression that resolves to one of the two values ( or ) and is then assigned to the variable .
To have a little fun with this, if you created this method:
And you called it like:
It would work fine. The problem is just that the C# grammar does not allow most naked expressions to live in a context in which the value of the expression is not consumed. (Remember, the defining difference between an expression and a statement is that an expression produces an expression, but a statement does not) Some expressions are allowed outside of this guidance -- for example invoking a method that returns a value. These become in the technical parlance an "expression statement". And usefully, the only candidates for expressions that can be promoted to statements are exactly delineated by the error message in your question's title.
Most of us think of assignments as statements, but it is more fundamentally an expression. (it returns the value assigned while simultaneously performing the assignment). That's why that empty call to will actually accomplish what you want. (not that it's very readable)
From your comment, I'll add this comment as part of my answer:
The only error of yours is the simple fact that the C# grammar doesn't allow it. It certainly could, but well, it does not. I'm reminded about how the when operator in SQL is an expression (meaning you can say set i = when x is null then 'A' else 'B') whereas in C# such a usage would be invalid (since the switch statement is not an expression -- it cannot return a value)