This page looks best with JavaScript enabled

VB.NET - When not to use Relaxed Delegate Conversion

 ·   ·  ☕ 2 min read

From MSDN:

  • Relaxed delegate conversion enables you to assign subs and functions to delegates or handlers even when their signatures are not identical.

In practice, it means that the following code:

1
2
3
Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
  MsgBox("Hello")
End Sub

Can be written like this:

1
2
3
Private Sub Button1_Click() Handles Button1.Click
  MsgBox("Hello")
End Sub

If you don’t need to use event arguments, such as in the above scenario, your code becomes much more readable by omitting argument clause.
For developers coming from C# background - yes, everything will work here, even with Option Strict On. Everything, but one thing.

Visual Studio has a useful feature, for which I don’t know the official name. Basically, when you mouse click on a WinForms control, it creates its default handler, or, if such handler is already present, navigates to the relevant location in code. Some click-to-jump-to-code, if I was asked to give it a name. Now, this feature stops working, if there is no exact match of signature between the original event and your handler. So even though your code would compile perfectly, VS designer will not help you navigating through it.

In comparison, having this in a C# Winforms application:

1
2
3
4
private void button1_Click()
{
  MessageBox.Show("Hello");
}

will not compile with this error:

  • No overload for ‘button1_Click’ matches delegate ‘System.EventHandler’.

Victor Zakharov
WRITTEN BY
Victor Zakharov
Web Developer (Angular/.NET)