The Ornery Ternary Operator

The Ornery Ternary Operator

C# has unfortunately inherited one of C/C++ and Java’s most opaque constructions, the ternary operator. The statement:

if ( a > b )

z = a;

else

z = b;

can be written extremely compactly as:

z = (a > b) ? a : b;

The reason for the original introduction of this statement into the C language was, like the post- increment operators, to give hints to the compiler to allow it to produce more efficient code, and to reduce typing when terminals were very slow. Today, modern compilers produce identical code for both forms given above, and the necessity for this turgidity is long gone. Some C programmers coming to C# find this an “elegant” abbreviation, but we don’t agree and will not be using it in this book.

 

Shashi Ray