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 eventExplanation
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
Units and Classes
Define units with interface and implementation sections.
VCL Form Basics
Create a form with event handlers in Delphi VCL.
Generics
Type-safe containers with generics in Delphi.
Interfaces and Reference Counting
Define interfaces with automatic reference counting.
Exception Handling
Try/Except/Finally in Delphi.
RTTI (Runtime Type Information)
Inspect types and properties at runtime.