Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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)))

You should check this via: if mType > High(TManagerType) then ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top