Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi typed constants in case statements

What is the most elegant (or least ugly) way of using typed constants in a case statement in Delphi?

That is, assume for this question that you need to declare a typed constant as in

const
  MY_CONST: cardinal = $12345678;
  ...

Then the Delphi compiler will not accept

case MyExpression of
  MY_CONST: { Do Something };
  ...
end;

but you need to write

case MyExpression of
  $12345678: { Do Something };
  ...
end;

which is error-prone, hard to update, and not elegant.

Is there any trick you can employ to make the compiler insert the value of the constant (preferably by checking the value of the constant under const in the source code, but maybe by looking-up the value at runtime)? We assume here that you will not alter the value of the "constant" at runtime.

like image 201
Andreas Rejbrand Avatar asked Jun 08 '10 16:06

Andreas Rejbrand


2 Answers

Depending on why you need the constant to be typed you can try something like

const
  MY_REAL_CONST = Cardinal($12345678);
  MY_CONST: Cardinal = MY_REAL_CONST;

case MyExpression of
  MY_REAL_CONST: { Do Something };
  ...
end;
like image 133
Uli Gerhardt Avatar answered Sep 21 '22 11:09

Uli Gerhardt


If you won't alter the value of the constant, then you don't need it to be a typed constant. The compiler can take the number you declare and correctly place it into whatever variable or parameter you assign it to. Typed constants are sort of a hack, and they're actually implemented as variables, so the compiler can't use them as constants whose value needs to be fixed at compile-time.

like image 40
Mason Wheeler Avatar answered Sep 23 '22 11:09

Mason Wheeler