That code should work just fine, right?

That code should work just fine, right?
Well it does not - it causes an AV...

type
  TNotifyProc = reference to procedure(Sender: TObject);

procedure Main;
var
  e: TNotifyEvent;
  p: TNotifyProc;
begin
  e := nil;
  p := e;
  if Assigned(p) then
    p(nil);
end;

Why? Because p := e creates an anonymous method that wraps the TNotifyEvent call. So In fact the compiler creates this:

p := procedure(Sender: TObject) begin e(Sender); end;

And now you see why it will cause an AV.

Conclusion: It is a bad idea to use anonymous methods as events that can be nil!

Comments