Skip to content
Delphi

Properties and Events

Define properties and event handlers in Delphi.

By EZ4Code Team
propertyeventobserver

Code

type
  TValueChanged = procedure(Sender: TObject; NewValue: Integer) of object;

  TCounter = class
  private
    FValue: Integer;
    FOnChange: TValueChanged;
    procedure SetValue(const Value: Integer);
  public
    constructor Create;
    property Value: Integer read FValue write SetValue;
    property OnChange: TValueChanged read FOnChange write FOnChange;
  end;

implementation

procedure TCounter.SetValue(const Value: Integer);
begin
  if FValue <> Value then
  begin
    FValue := Value;
    if Assigned(FOnChange) then
      FOnChange(Self, FValue);
  end;
end;

// Usage
procedure TForm1.CounterChanged(Sender: TObject; NewValue: Integer);
begin
  Caption := 'Count: ' + IntToStr(NewValue);
end;

var C: TCounter;
C := TCounter.Create;
C.OnChange := CounterChanged;
C.Value := 10;  // triggers event

Explanation

Properties use read/write specifiers (direct field or method). Events are method pointers (of object). Assigned checks if a handler is set — always check before calling. Setter methods enable validation and side effects (like firing events). This pattern implements the Observer pattern.

More Delphi Snippets