Using Object Variables

From RAD Studio
Jump to: navigation, search

Go Up to Using the object model Index

You can assign one object variable to another object variable if the variables are of the same type or are assignment compatible. In particular, you can assign an object variable to another object variable if the type of the variable to which you are assigning is an ancestor of the type of the variable being assigned. For example, here is a TSimpleForm type declaration and a variable declaration section declaring two variables, AForm and Simple:

type
  TSimpleForm = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
  private
    { Private declarations }
  public
    { Public declarations }
  end;
var
  AForm: TForm;
  SimpleForm: TSimpleForm;

AForm is of type TForm, and SimpleForm is of type TSimpleForm. Because TSimpleForm is a descendant of TForm, this assignment statement is legal:

AForm := SimpleForm;

Suppose you write an event handler for the OnClick event of a button. When the button is clicked, the event handler for the OnClick event is called. Each event handler has a Sender parameter of type TObject:

procedure TForm1.Button1Click(Sender: TObject);
begin
.
.
.
end;

Because Sender is of type TObject, any object can be assigned to Sender. The value of Sender is always the control or component that responds to the event. You can test Sender to find the type of component or control that called the event handler using the reserved word is. For example,

if Sender is TEdit then
  DoSomething
else
  DoSomethingElse;

See Also