The TMenuItem.OnClick event always provides in the parameter an instance of the TMenuItem class, so checking the parameter type is not needed. Of course unless someone calls the event from the code level and gives the object another of class, but this should not be done, because TMenuItem has the Click method.
You're right, of course; in fact that's what I do always: just call
AMenuItem.Click if needed--same with the other classes that have a
Click method, like
TButton.
It's just that, after having been burned quite a few times, now I always check Sender against the needed class. Beter safe than sorry, I always say
The one thing I don't like about your proposal is the unneccessary use of
absolute. It's maybe a knee-jerk reaction nut since soft-casting with
as is readily available, I wouldn't use it. If anything, to avoid extra typing if Sender is referenced many times, I would just do:
procedure TForm.MenuItemClick(ASender: TObject);
var
AMenuItem: TMenuItem;
begin
AMenuItem := Sender as TMenuItem;
Caption := DefaultCaption + AMenuItem.Caption;
{... etc ...}
end;
RE . setting the form's caption, maybe it would be better to generalize the process with something like:
TForm1.BuildCaption(AnObject: TObject): String;
begin
Result := DefaultCaption;
if Assigned(AnObject) then begin
if AnObject.InheritsFrom(TControl) then
Result := Result + (AnObject as TControl).Caption
else if AnObject.InheritsFrom(TMenuItem) then
Result := Result + (AnObject as TMenuItem).Caption;
{ add other components with Caption which don't inherit from TControl }
end;
end;