Ternary operator

Top  Previous  Next

What is translated > Operators > Ternary operator

The inline-if (ternary) operator was introduced in Delphi 13.

 

It has the following form:

 

if <condition> then <expr1> else <expr2>

 

It evaluates <condition> and returns either <expr1> or <expr2>.

 

Translation to C#

 

The expression is translated directly to the C# ternary operator:

 

<condition> ? <expr1> : <expr2>

 

Examples

 

Simple expression

 

X := if A > 0 then 1 else 2;

X = (A > 0) ? 1 : 2;

 

Nested expression

 

X := if A > 0 then (if B > 0 then 1 else 2) else 3;

X = (A > 0) ? ((B > 0) ? 1 : 2) : 3;

 

Inside a larger expression

 

S := 'X' + (if Flag then 'Y' else 'Z');

S = "X" + (Flag ? "Y" : "Z");

 

Notes

 

The operator has low precedence

-> Parentheses may be added in C# to preserve evaluation order.

Both branches must be type compatible

-> Explicit casts may be required in C#.

The operator is lazy (only one branch is evaluated)

-> This matches the behavior of the C# ternary operator.



This page belongs to the Delphi2C# Documentation

Delphi2C# home  Content