C# Ternary Operator Without Assignment Management

?: Operator (C# Reference)

The conditional operator (), commonly known as the ternary conditional operator, returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.

The must evaluate to or . If is , is evaluated and becomes the result. If is , is evaluated and becomes the result. Only one of the two expressions is evaluated.

Either the type of and must be the same, or an implicit conversion must exist from one type to the other.

You can express calculations that might otherwise require an construction more concisely by using the conditional operator. For example, the following code uses first an statement and then a conditional operator to classify an integer as positive or negative.

The conditional operator is right-associative. The expression is evaluated as , not as .

The conditional operator cannot be overloaded.

Example

See Also

C# Reference
C# Programming Guide
C# Operators
if-else
?. and ?Operators
?? Operator

?? Operator (C# Reference)

The operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

A nullable type can represent a value from the type’s domain, or the value can be undefined (in which case the value is null). You can use the operator’s syntactic expressiveness to return an appropriate value (the right hand operand) when the left operand has a nullable type whose value is null. If you try to assign a nullable value type to a non-nullable value type without using the operator, you will generate a compile-time error. If you use a cast, and the nullable value type is currently undefined, an exception will be thrown.

For more information, see Nullable Types.

The result of a ?? operator is not considered to be a constant even if both its arguments are constants.

Example

See Also

C# Reference
C# Programming Guide
C# Operators
Nullable Types
What Exactly Does 'Lifted' mean?

Categories: 1

0 Replies to “C# Ternary Operator Without Assignment Management”

Leave a comment

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *