Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi Check variable value in Type Declaration

How can I determine if the value of a variable is within the range of a Type Declaration. Ex.

Type
  TManagerType = (mtBMGR, mtAMGR, mtHOOT);

...

var
  ManagerType: TManagerType;

....


procedure DoSomething;
begin
  if (ManagerType in TManagerType) then
    DoSomething
  else
    DisplayErrorMessage;
end;

Thanks, Pieter.

like image 932
Pieter van Wyk Avatar asked Oct 20 '25 16:10

Pieter van Wyk


2 Answers

InRange: Boolean;
ManagerType: TManagerType;
...
InRange := ManagerType in [Low(TManagerType)..High(TManagerType)];

As Nickolay O. noted - whilst boolean expression above directly corresponds to:

(Low(TManagerType) <= ManagerType) and (ManagerType <= High(TManagerType))

compiler does not perform optimization on checking membership against immediate set based on single subrange. So, [maturely] optimized code will be less elegant.

like image 164
Free Consulting Avatar answered Oct 24 '25 03:10

Free Consulting


Well, a variable of type TManagerType has to be in that range since that's how Pascal enumerated types work. The only way it could not be is if you have done something naughty behind the compiler's back.

Another way to write this would be:

InRange(ord(ManagerType), ord(low(ManagerType)), ord(high(ManagerType)))
like image 42
David Heffernan Avatar answered Oct 24 '25 02:10

David Heffernan