C# contains a single operator that handles conditional logic in a single statement. It is generally written as "?:" (making it difficult to find using a search engine) and it is often referred to as the conditional operator, although the official documentation does not give it this name.
I write about it here, not because it is new or extra cool, but because I believe it is underused by C# developers.
The syntax is:
condition ? ValueIfTrue : ValueIfFalse;
- condition is a boolean expression to test
- ValueIfTrue is the value to return if the condition expression is true
- ValueIfFalse is the value to return if the condition expression is false
An example should clarify this:
The output of this code snippet is:
x >= 0 ? "Positive" : "Negative";
returns the string "Positive" if x is at least 0 and "Negative" if x is less than 0.
Of course the same expression could be written like the following:
But this requires more typing (which provides more changes for errors); and (more importantly), it takes more time to read, so it cannot be digested as quickly by someone reviewing the code later. Of course, I'm assuming that the code reviewer is familiar with this operator, but I don't think that's an unreasonable expectation, given that it has been in the C# language over 10 years.
Many developers are not familiar with ?: operator, but they should be. It simplifies code and makes it easier to read.
Here is the full code of a console application demonstrating these concepts: