is there a way to reference an object instance that is created using the "with" statement?
Example:
with TAnObject.Create do
begin
DoSomething(instance);
end;
Where DoSomething would use the instance reference as if you were passing an instance from a variable declared reference to the object created.
Example:
AnObject := TAnObject.Create;
Thanks.
You should never use
with
either because future changes might introduce more into that scope than you intended.Take this for instance:
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.
You gave the answer yourself: declare local variable. If you want you can use the with keyword on that.
In above example the only reason to use with is code readability, which is very subjective, you could also ditch the with keyword and use MyInstance directly. It's just a matter of personal taste. I don't agree on the "never use with" answers, but you should be aware of it's drawbacks.
See also this question: Is delphi "with" keyword a bad practice?
You should use
Self
.Example:
In that context
Self
is the object created bywith
clause.Well, you can use such approach:
or class helpers:
But, actually, previous replies are correct: you should better forget about "with" statement.
I've learnt the hard way - only use 'With' in the following scenarios:
i.e keep the visibility of With as simple as possible. When you take into account the fact that the debugger cant resolve 'With', it's actually better and clearer to use a simple local variable or to fully declare the target i.e MyRecord.Something
This is not possible now, but we can make it a reality by persuading the compiler creators:
My proposal is: