Name

With Keyword

Syntax

with Expression do Statement

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:

  1. Members of records, objects, classes, or interfaces listed in the with statement, starting with the last or innermost with statement, and continuing with earlier or outer with statements.

  2. Local variables and subroutine parameters, including implicitly defined variables, such as Result and Self.

  3. Members of Self (if the subroutine is a method). You can think of every method as having an implicit with Self do before the method body.

  4. Global variables in the same unit as the reference.

  5. 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 the with 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.