Sunday, 3 February 2013

How to use Conditional Operators in Delphi XE2?

How to use Conditional Operators in Delphi XE2?

Conditional operators look so attractive because they let you write short and concise code. But delphi does not provide any conditional operators.

Lets have following example of conditional operators.

if a>b then
c:= 1
c:= 0;

I want to conclude it in one line using conditional operators like in C/C++.

c := (a > b ? 1 : 0);

But no, this is not possible in delphi. I don't know why? Why conditional operators are not included in delphi?

Workaround of Conditional Operators in Delphi?

Delphi provides a set of IfThen functions in the Math and StrUtils units. Delphi prism provides the utility of Iif that only evaluates one of its two value parameters. For example:

c:= Iif(a > b, 1, 0);

There are a number of available simple type handles on the overloaded IFTHEN function.

StrUtils.IfThen (String)
Math.IfThen (Integer)
Math.IfThen (Int64)
Math.IfThen (Double) (works for TDateTime as well)

Having or not having conditional operators don't make any difference because conditional operators have some drawbacks like less readability: Delphi is more centered on readability than the C Syntax languages which are more centered on character power (as much information per character as possible). The conditional operator is powerful but not readable.

No comments:

Post a Comment