Syntax for adding an event handler in VB.NET

I have the following code that I need to convert to VB.NET. The problem is that every translation tool that I found incorrectly converts a part of the handler. I can't seem to do it myself.

FtpClient ftpClient = new FtpClient(); ftpClient.UploadProgressChanged += new EventHandler<UploadProgressChangedLibArgs>(ftpClient_UploadProgressChanged); ftpClient.UploadFileCompleted += new EventHandler<UploadFileCompletedEventLibArgs>(ftpClient_UploadFileCompleted); 
+6
source share
1 answer

There are two ways to associate event handler methods with an event in VB.NET.

The first involves the use of the Handles , which you add to the end of the event handler method definition. For instance:

 Sub ftpClient_UploadProgressChanged(sender As Object, e As UploadProgressChangedLibArgs) Handles ftpClient.UploadProgressChanged ' ... End Sub Sub ftpClient_UploadFileCompleted(sender As Object, e As UploadFileCompletedEventLibArgs) Handles ftpClient.UploadFileCompleted ' ... End Sub 

The first method is much simpler if you have already received separately defined event handler methods (i.e. if you do not use lambda syntax). I would recommend it whenever possible.

The second involves explicitly using the AddHandler operator, like += in C #. This is the one you need to use if you want to dynamically bind event handlers, for example. if you need to change them at runtime. So your code literally converted will look like this:

 Dim ftpClient As New FtpClient() AddHandler ftpClient.UploadProgressChanged, AddressOf ftpClient_UploadProgressChanged AddHandler ftpClient.UploadFileCompleted, AddressOf ftpClient_UploadFileCompleted 

As you said, I tried running your code through the Developer Fusion converter and was surprised to see that they were returning invalid VB.NET code:

 ' WRONG CODE! Dim ftpClient As New FtpClient() ftpClient.UploadProgressChanged += New EventHandler(Of UploadProgressChangedLibArgs)(ftpClient_UploadProgressChanged) ftpClient.UploadFileCompleted += New EventHandler(Of UploadFileCompletedEventLibArgs)(ftpClient_UploadFileCompleted) 

It turns out a well-known mistake for which one could vote!

+10
source

Source: https://habr.com/ru/post/948883/


All Articles