Search code examples
delphiordinal

invalid typecast when Ninth enumeration added


I have inherited some code that I need to modify. The original is essentially what is below. I need to add a ninth item to the enumeration list but when I do, I get an invalid typecast at "ord(byte(ts))";

program OrdTest;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils;

type
  TFlag = (tsOne, tsTwo, tsThree, tsFour, tsFive, tsSix, tsSeven, tsEight); // , tsNine
  TStatus = set of TFlag;

function GetStatus(i: integer): TStatus;
var
  ts: TStatus;
  j: smallint;
begin
  try
    ts := GetStatus(4);  // returned from a table

    j := ord(byte(ts)); // Invalid typecast
  except
    on E: Exception do
      Writeln(E.Message)
  end;

end;

end.

since a byte can be any valid to 255, I don't understand the exception.

What can I do so that I can add a ninth enumeration and still have the code function?


Solution

  • Before you added tsNine you had 8 enum values, so a set of them took 8 bits and fitted into a Byte. Now you have 9 bits and need a Word to fit the set in. Therefore you'll have to cast to Word now. You can check SizeOf(ts) to see this for yourself.