On Sat, Jul 13, 2019 at 2:37 PM Ondrej Pokorny <laza...@kluug.net> wrote:

> I do exactly the same - check the low/high bounds in a type helper :)
> Yes, and I am tired of typing it as well :)
>

You can pretty easily write a generic function that will work on pretty
much any enum for this, BTW:

program Example;

{$mode Delphi}

uses TypInfo, SysUtils;

function TryConvert<T>(const Value: SizeInt): T; inline;
begin
  if (Value >= SizeInt(Low(T))) and (Value <= SizeInt(High(T))) then
    Result := T(Value)
  else
    raise EConvertError.Create(
      Format(
        'Invalid value for %s : %d', [
          PTypeInfo(TypeInfo(T))^.Name,
          Value
        ]
      )
    );
end;

type
  Letter = (A, B, C);

begin
  WriteLn(TryConvert<Letter>(0));
  WriteLn(TryConvert<Letter>(1));
  WriteLn(TryConvert<Letter>(2));
  // Exception!
  WriteLn(TryConvert<Letter>(3));
end.

The exception printing "EConvertError: Invalid value for Letter : 3", of
course.
_______________________________________________
fpc-devel maillist  -  fpc-devel@lists.freepascal.org
https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-devel

Reply via email to