Delphi typed constants in case statements

What is the most elegant (or least ugly) way to use typed constants in a case in Delphi?

That is, suppose 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, is hard to update, not elegant.

Is there any trick you can use to force the compiler to insert a constant value (preferably by checking the constant value in const in the source code, but perhaps by looking at the value at runtime)? We assume that you will not change the value of "constant" at runtime.

+6
delphi case-statement
source share
3 answers

Depending on why you need to enter a constant, you might try something like

 const MY_REAL_CONST = Cardinal($12345678); MY_CONST: Cardinal = MY_REAL_CONST; case MyExpression of MY_REAL_CONST: { Do Something }; ... end; 
+12
source share

If you do not change the value of a constant, you will not need its typed constant. The compiler can accept the number you declare and correctly place it in any variable or parameter to which you assigned it. Typed constants are a kind of hack, and they are actually implemented as variables, so the compiler cannot use them as constants, the value of which must be fixed at compile time.

+4
source share

Typed constants cannot be used in case statements, since a typed constant is actually a more static variable (and assignable ...) and therefore cannot be used in the case case, which expects constants.

0
source share

All Articles