Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums vs Const vs Class Const in Delphi programming

Tags:

delphi

I have an integer field in a ClientDataSet and I need to compare to some values, something like this:

I can use const

const
  mvValue1 = 1;
  mvValue2 = 2;

if ClientDataSet_Field.AsInteger = mvValue1 then

or enums

TMyValues = (mvValue1 = 1, mvValue2 = 2);

if ClientDataSet_Field.AsInteger = Integer(mvValue1) then

or class const

TMyValue = class
const
   Value1 = 1;
   Value2 = 2;
end;

if ClientDataSet_Field.AsInteger = TMyValues.Value1 then

I like the class const approach but it seems that is not the delphi way, So I want to know what do you think

like image 857
Marioh Avatar asked Dec 19 '08 21:12

Marioh


People also ask

What is difference between enum and const variable?

Solution 1. No, enum is a type that defines named values, a constant variable or value can be any type. You use an enum variable to hold a value of the enum type, you use a const to define a variable that cannot change and whose value is known at compile time.

What is a constant in Delphi?

A const parameter clearly tells the reader that the subroutine does not change the parameter's value. This improves the readability and clarity of the code. The compiler enforces the restriction. If you accidentally try to assign a new value to a const parameter, the compiler issues an error message.


1 Answers

Declaration:

type
  TMyValues = class
    type TMyEnum = (myValue1, myValue2, myValue3, myValue4);
    const MyStrVals: array [TMyEnum] of string =
      ('One', 'Two', 'Three', 'Four');
    const MyIntVals: array [TMyEnum] of integer =
      (1, 2, 3, 4);
  end;

Usage:

if ClientDataSet_Field.AsInteger = TMyValues.MyIntVals[myValue1] then

A cast would generally be my last choice.

like image 126
Jim McKeeth Avatar answered Nov 11 '22 12:11

Jim McKeeth