Kyle Uithoven
Kyle Uithoven

Reputation: 2444

Passing Method as Delegate Parameter Issues

I'm used to programming in C# so I have no idea how to approach delegates and passing methods in VB

The error that I am getting is: Argument not specified for parameter 'message' of 'Public Sub ReceiveMessage(message As String)'

Here is the constructor of the class that I am trying to pass to:

Delegate Sub ReceiveDelegate(message As String)
Public ReceiveMethod As ReceiveDelegate

Sub New(ByRef receive As ReceiveDelegate)
    ReceiveMethod = receive
End Sub

This is the method that I am trying to pass to that constructor:

Public Sub ReceiveMessage(message As String)
        MessageBox.Show(message)
End Sub

I'm using it as such:

Dim newClass As New Class(ReceiveMessage)

The purpose of this, is that once the class receives data from a network device, it can call the corresponding method on the Form asynchronously.

Upvotes: 1

Views: 865

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

You need to create the delegate object and use the AddressOf operator, like this:

Dim newClass As New Class(New ReceiveDelegate(ReceiveMessage))

However, if you don't explicitly create the delegate object, VB.NET will automatically determine the right type, based on the signature, and create it for you, so you can just do it like this:

Dim newClass As New Class(AddressOf ReceiveMessage)

The latter is obviously less typing, but the former is more explicit. So, take your pick. Both ways are perfectly acceptable and common.

Upvotes: 1

Related Questions