Name

Write Directive

Syntax

property Name: Type ... write Setter;

Description

A property’s write directive tells Delphi how to change the property’s value. The Setter can be the a field reference or a method name in the class or in an ancestor class.

If the Setter is a field, the field’s type must be the same as the property’s type. The usual access rules apply, so the field cannot be a private field of an ancestor class unless the ancestor class is in the same unit. Typically, the field is a private field of the same class that declares the property.

The field can be an aggregate (record or array), and the Setter must specify a record member or array element (at a constant index) of the appropriate type. Records and arrays can be nested.

If the Setter is a method, the method must be a procedure whose argument type is the same as the property type. The method can be static or virtual, but it cannot be a dynamic method or message handler.

If the property is indexed or an array property, the Setter must be a method. The first parameter is the index value, which is an Integer. Subsequent arguments are the array indices. The type of each Setter argument must match the type of the corresponding array index. The last argument is the new property value.

When the user assigns to the property value, Delphi assigns the value to the Setter field or calls the Setter method.

Tips and Tricks

  • If you use a Setter field, Delphi compiles all property references into direct field references, so there is no performance penalty for using a property instead of a field.

  • If a published property has a class type (other than TComponent or one of its descendants), you should define a Setter method that calls the object’s Assign method:

type
  TDemo = class(TComponent)
  private
    Font: TFont;
    procedure SetFont(NewFont: TFont);
  public
    constructor Create(Owner: TComponent); override;
    destructor Destroy; override;
  published
    property Font: TFont read fFont write SetFont;
  end;

procedure TDemo.SetFont(NewFont: TFont);
begin
  Font.Assign(NewFont);
end;
  • A good programming style is to make all fields private and declare protected, public, or published properties to access the fields. If you need to modify the class at a later date, you can change the field to a method without affecting any code that depends on the class and its property.

Example

See the property keyword for examples.

See Also

Class Keyword, Index Directive, Property Keyword, Read Directive
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset