TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
?: operator, formally known as the ternary conditional operator, evaluates a boolean expression and returns the result of one of two mutually exclusive expressions based on that evaluation. It is an expression-based construct, meaning it resolves to a value, unlike the statement-based if-else control flow.
Evaluation Mechanics
The operator requires three operands:condition: An expression that must be implicitly convertible tobool, or a type that explicitly overloads thetrueandfalseoperators.consequent: The expression evaluated and returned if theconditionevaluates totrue.alternative: The expression evaluated and returned if theconditionevaluates tofalse.
condition is true, consequent is evaluated and alternative is ignored. If condition is false, alternative is evaluated and consequent is ignored.
Type Resolution
The compiler must determine a single return type for the entire ternary expression. The rules for type resolution depend on the C# version:- Standard Type Resolution: There must be an implicit conversion from the type of the
consequentto the type of thealternative, or vice versa. If neither conversion exists, or if both exist (creating an ambiguity), the compiler throws an error. - Target-Typed Conditional Expressions (C# 9.0+): If the
consequentandalternativedo not share a common type, the expression is valid provided both types are implicitly convertible to the target type of the assignment or context.
Associativity
The ternary operator is right-associative. When multiple conditional operators are chained, they are grouped from right to left.Ref Conditional Operator
Starting with C# 7.2, the ternary operator can be used to return a variable reference (ref) rather than a value. Both the consequent and alternative must be ref expressions of the exact same type. When assigning the result to a ref local, the entire ternary expression must be enclosed in parentheses to parse correctly.
Restrictions
- The
?:operator cannot be overloaded via user-defined operator overloading. - Because it is an expression, it cannot be used as a standalone statement; its result must be assigned, passed as an argument, or returned.
Master C# with Deep Grasping Methodology!Learn More





