Search code examples
delphidelphi-2009record

Delphi - records with variant parts


I want to have a record (structure) with a 'polymorphic' comportment. It will have several fields used in all the cases, and I want to use other fields only when I need them. I know that I can accomplish this by variant parts declared in records. I don't know if it is possible that at design time I can access only the elements I need. To be more specific, look at the example bellow

program consapp;

{$APPTYPE CONSOLE}

uses
  ExceptionLog,
  SysUtils;

type
  a = record
   b : integer;
   case isEnabled : boolean of
    true : (c:Integer);
    false : (d:String[50]);
  end;


var test:a;

begin
 test.b:=1;
 test.isEnabled := False;
 test.c := 3; //because isenabled is false, I want that the c element to be unavailable to the coder, and to access only the d element. 
 Writeln(test.c);
 readln;
end.

Is this possible?


Solution

  • All variant fields in a variant record are accessible at all times, irrespective of the value of the tag.

    In order to achieve the accessibility control you are looking for you would need to use properties and have runtime checks to control accessibility.

    type
      TMyRecord = record
      strict private
        FIsEnabled: Boolean;
        FInt: Integer;
        FStr: string;
        // ... declare the property getters and settings here
      public
        property IsEnabled: Boolean read FIsEnabled write FIsEnabled;
        property Int: Integer read GetInt write SetInt;
        property Str: string read GetString write SetString;
      end;
    ...
    function TMyRecord.GetInt: Integer;
    begin
      if IsEnabled then
        Result := FInt
      else
        raise EValueNotAvailable.Create('blah blah');
    end;