Wednesday, September 21, 2005

Delphi CLR multicast events explored

In a recent blogpost, I compared the C# and Delphi languages regarding to events. This time I will dig a little deeper in the Delphi .NET multicast events.

In the original Delphi VCL (since 1995), multicast events are not supported. Events, in VCL, are properties which can be assigned using the read/write methodoligy. They are limited to one handler for one event.
In Delphi .NET multicast events are, just like in C#, supported. In C# multiple listners(handlers) can be added and removed with the += and -= operators.
In Delphi for .NET you can achieve the same behaviour with the Include and Exclude methods.

The following example adds an extra handler to a button click:

Include(MyButton.Click, MyExtraEventHandler);

to remove it use:

Exclude(MyButton.Click, MyExtraEventHandler);

MyExtraEventHandler is a procedure declared as follows:

procedure TfrmMain.MyExtraEventHandler(sender : System.Object; e : System.Eventargs);
(Any procedure is OK as long as the parameters compare)

Note that adding a handler multiple times causes this handler to fire multiple times. Removing a non existing handler, however, does not generate a runtime error.

Adding multicast events to an object:

To use multicast events you must declare them using the add and remove keywords. Read and writing for those events are not allowed. The compiler will generate an error "Read/Write not allowed for CLR events".
You can, if you like, use single cast events using the read and write style, just as in the VCL. In fact you could use a TNotifyEvent, but that is another story)

An add/remove example:

TMyObject = class
private
FBeforeSomething : System.EventHandler;
public
property BeforeSomething : System.EventHandler add FBeforeSomething remove FBeforeSomething;
procedure FireTheEvent;
end;

You can add eventhandlers, just like the above example, using the include and exclude methods:
MyObject := TMyObject.Create;
Include(MyObject.BeforeSomething, AnEventHandler);
Include(MyObject.BeforeSomething, AnOtherEventHandler);

So compared to VCL read/write events CLR events are not that difficult to understand. The main differents is that they are hooked up using the Include and Exclude methods.

3 comments:

Anonymous said...

Maybe a stupid question, but since you can add the same event multiple times will it take the same number of calls to Exclude to remove it or will just one do the trick?

Roland said...

It will take the same number of calls. I can't think of any reason yet why one should add the same eventhandler multiple times.

Roland said...

C# behaves exactly the same as Delphi, so I guess it is CLR events nature.