is there a way to reference an object instance that is created using the \"with\" statement?
Example:
with TAnObject.Create do
begin
DoSomething(in
You should never use with
either because future changes might introduce more into that scope than you intended.
Take this for instance:
procedure Test;
var
x: Integer;
begin
with TSomeObject.Create do
begin
DoSomethingWithX(x);
Free;
end;
end;
and then later on you tuck on a X property on the TSomeObject class. Now, which X do you think it's going to use? The local variable or the X property of the object?
The best solution is always to just create a local variable with a short name, and alias the object to that variable.
procedure Test;
var
x: Integer;
o: TSomeObject;
begin
o := TSomeObject.Create;
o.DoSomethingWithX(x);
o.Free;
end;
An addition to Brian's example on a Notify handler is to use an absolute variable (win32 only):
procedure Notify( Sender : TObject );
var
Something : TSomeThing absolute Sender;
begin
if Sender is TSomething then
begin
VerySimpleProperty := Something.Something;
OtherProperty := Something.SomethingElse;
end;
end;
It basically avoids having to assign a local variable or have a lot of type casts.
for FMX, you should use GetObject example:
with TLabel.Create(box1) do
begin
Font.Size := 34;
Font.Style := [TFontStyle.fsBold];
TextAlign := TTextAlign.taCenter;
box1.AddObject(GetObject);
end;;