Jump to content
Sign in to follow this  
Jacek Laskowski

Helper trick ;-)

Recommended Posts

As you know, helpers on the one hand are a neat solution, on the other hand they are only syntactic sugar. They have a lot of restrictions, including the lack of the possibility to add fields, but ...
Today, when I was writing a helper I tried something like this:

 

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
  MyInt = type Int64;

  MyIntHelper = record helper for MyInt
  private
  {$WRITEABLECONST ON}
  const fInitialized : Boolean = False;
  {$WRITEABLECONST OFF}
  protected
    procedure Initialize();
  public
    function ToString(): string;
  end;

procedure MyIntHelper.Initialize();
begin
  if not fInitialized then
  begin
    Self := 123456;
    fInitialized := True;
  end;
end;

function MyIntHelper.ToString(): string;
begin
  Initialize;
  Result := IntToStr(self);
end;

var
  i : MyInt;

begin
  try
  Writeln(i.ToString);
  Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

 

And it works 😉

Share this post


Link to post
Guest

... not really

 

var
  i,j : MyInt;

begin
  try
  Writeln(i.ToString);
  Writeln(j.ToString);
  Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

results in

123456
0

global state was never a problem with helpers but a real field for each instance is not possible.

Edited by Guest

Share this post


Link to post
Guest
18 minutes ago, Jacek Laskowski said:

You destroy my day 😉

No, I stopped you before you hit the wall - I saved your day

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×