Search code examples
delphiooplanguage-featuresselfdelphi-prism

Why is Self assignable in Delphi?


This code in a GUI application compiles and runs:

procedure TForm1.Button1Click(Sender: TObject);
begin
  Self := TForm1.Create(Owner);
end;

(tested with Delphi 6 and 2009)

  • why is Self writable and not read-only?
  • in which situations could this be useful?

Edit:

  • is this also possible in Delphi Prism? (I think yes it is, see here)

Update: Delphi applications/libraries which make use of Self assignment:


Solution

  • That's not as bad as it could be. I just tested it in Delphi 2009, and it would seem that, while the Self parameter doesn't use const semantics, which you seem to be implying it should, it also doesn't use var semantics, so you can change it all you want within your method without actually losing the reference the caller holds to your object. That would be a very bad thing.

    As for the reason why, one of two answers. Either a simple oversight, or what Marco suggested: to allow you to pass Self to a var parameter.