Name
With Keyword
Syntax
withExpression
doStatement
Description
The with
statement adds a record, object, class,
or interface reference to the scope for resolving symbol names.
Delphi searches for names in the following order:
Members of records, objects, classes, or interfaces listed in the
with
statement, starting with the last or innermostwith
statement, and continuing with earlier or outerwith
statements.Local variables and subroutine parameters, including implicitly defined variables, such as
Result
andSelf.
Members of
Self
(if the subroutine is a method). You can think of every method as having an implicit withSelf
do before the method body.Global variables in the same unit as the reference.
Global variables declared in other units, starting with the last unit named in the
uses
declaration.
Tips and Tricks
Be careful using the
with
statement. Indiscriminate use of thewith
statement obscures the meaning of code and makes it harder to identify the object references that are the targets of methods and properties. Changes to the referenced record, object, class, or interface can cause an identifier to be interpreted in a different scope. If you are fortunate, the change will cause a syntax error; if you are not, the change will not be noticed until your program performs incorrectly.Nonetheless,
with
has its uses. It can be a convenient way to avoid creating a temporary variable when adding such a variable does not contribute to the clarity of your code.
Example
// When the user ...
Get Delphi in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.