Name
With Keyword
Syntax
withExpressiondoStatement
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
withstatement, starting with the last or innermostwithstatement, and continuing with earlier or outerwithstatements.Local variables and subroutine parameters, including implicitly defined variables, such as
ResultandSelf.Members of
Self(if the subroutine is a method). You can think of every method as having an implicit withSelfdo 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
usesdeclaration.
Tips and Tricks
Be careful using the
withstatement. Indiscriminate use of thewithstatement 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,
withhas 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access