In my previous post on the handling of COM events I described how I was driven into the arms of VB.NET. A VB.NET class published to COM sinks events as desired, a C# class pops up a mysterious error 459. With the help of feedback I've been delving a little deeper into this.
Events are handled by event handling methods. The way to set these in C# is by adding a delegate object to the event :
FileSystemWatcher watcher = new FileSystemWatcher(dirName, filter); watcher.Created += new FileSystemEventHandler(watcher_Created);
...
privatevoid watcher_Created(object sender, FileSystemEventArgs e) { // Do something }
The usual way to set event handlers in VB is by using the handles keyword :
PrivateWithEvents fw AsNew FileSystemWatcher
PrivateSub watcher_Created(ByVal sender AsObject, ByVal e As FileSystemEventArgs) Handles fw.Created 'Do something EndSub
The nice way about the C# syntax is that it's no problem to hook in multiple methods as event handler's to the same event:
watcher.Created += new FileSystemEventHandler(watcher_Created); watcher.Created += new FileSystemEventHandler(anotherwatcher);
You can do the same thing, in VB.NET. In my post I admitted not knowing how to do that, Seanpointed me to the syntax to get that done using the AddHandler keyword. Instead of using handles the code could be written as
PublicClass Class1 PrivateWithEvents fw AsNew FileSystemWatcher PrivateSub watcher_Created(ByVal sender AsObject, ByVal e As FileSystemEventArgs) 'Do something EndSub
The handles keyword does translates to an AddHandler statement. But instead of in the constructor this statement is in the property setter of the object whose event is handled and adds the delegate to the internal object instead of its property wrapper. Apparently this subtle difference is enough to provide COM with a good event support. It matches the somewhat cryptic description Although you might think you could sink the events from the implemented object, that isn't automatically the caseon msdn.
The difference between C# and VB.NET is not the language itself but the code generation, I would not know of a way to alter that.