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);
...
private void watcher_Created(object sender, FileSystemEventArgs e)
{
// Do something
}
The usual way to set event handlers in VB is by using the handles keyword :
Private WithEvents fw
As New FileSystemWatcher
Private Sub watcher_Created(ByVal sender As Object, ByVal e As FileSystemEventArgs) Handles fw.Created
'Do something
End Sub
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, Sean pointed me to the syntax to get that done using the AddHandler keyword. Instead of using handles the code could be written as
Public Class Class1
Private WithEvents fw As New FileSystemWatcher
Private Sub watcher_Created(ByVal sender As Object, ByVal e As FileSystemEventArgs)
'Do something
End Sub
Public Sub New()
AddHandler fw.Created, AddressOf watcher_Created
End Sub
End Class
Using this syntax I found out my VB.NET COM class started popping up
the same 459 errors as the C# class. Apparently I was on to something.
Inspecting the actual code using Reflector shows that Handles and AddHandler have a subtle difference in the generated code.
The disassembly of a class using handles
constructor .ctor()
Property setter of the object whose events are handled
The disassmbly of the class when it sets the event handler in the constructor
Constructor .ctor
Fw property setter
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 case on 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.
Posted
Tue, Aug 2 2005 7:56 PM
by
pvanooijen