The ? operator
The if-else
statements are so common and widely used in C# that a specialized shorthand notation is available for writing simpler ones, without resorting to the full multiline if-else
statements. This shorthand is called the ?
operator. The basic form of this statement is as follows:
//If condition is true then do expression 1, else do expression 2 (condition) ? expression_1 : expression_2;
Let's see the ?
operator in a practical example as shown here:
//We should hide this object if its Y position is above 100 units
bool ShouldHideObject = (transform.position.y > 100) ? true : false;
//Update object visibility
gameObject.SetActive(!ShouldHideObject);
Tip
The ?
operator is useful for shorter statements, but for long and more intricate statements, it can make your code harder to read.