H. Pauwelyn ツ H. Pauwelyn ツ - 10 months ago 82
Vb.net Question

WhitEvent and AddHandler in VB

I asking myself what the differences are between

Dim WithEvents EClass As New EventClass


AddHandler Obj.XEvent, AddressOf Me.XEventHandler

In which context you should use the first or the second?

Can anyone explain it? Thanks


WithEvents supports the Handles keyword. Which you can apply to a method. When the VB.NET compiler encounters it, it will generate code in the constructor of the class that automagically calls AddHandler. So you don't have to write it yourself.

It is pretty convenient to designers, both the WPF and the Winforms designers rely on it for example. It eliminates the likelihood that you get a build error when you delete an event handler, you can't forget to also delete the AddHandler statement. And it is very compatible with code written in previous versions of Visual Basic, like VB6. Which makes it easier to convert old projects. Probably the major reason WithEvents was implemented in .NET, C# does not have anything similar.

There's also a good reason to really dislike it. There's a nasty problem with it that to this day still has not been solved. In order to support Edit and Continue, the compiler creates WeakReferences in the Debug build. The debugger ensures that those WeakReference objects are cleaned up again. That does not happen when you run without a debugger. That's a leak that will eventually crash your program, albeit that it takes a while. This makes it very important that you only ever deploy the Release build of a VB.NET program.