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:
to remove it use:
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
FBeforeSomething : System.EventHandler;
property BeforeSomething : System.EventHandler add FBeforeSomething remove FBeforeSomething;
You can add eventhandlers, just like the above example, using the include and exclude methods:
MyObject := TMyObject.Create;
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.