How should parameter to function be given when AddressOf used?

See the following code:

Public Sub MyFunction1(ByVal CodeNo As Integer)

    Dim thread As New Thread(AddressOf MyFunction2)
    thread.Start()

End Sub

Private Sub MyFunction2(ByVal CodeNo As Integer)

    Debug.Print CodeNo

End Sub

How should a parameter value be supplied to MyFunction2?

Why is the compiler letting this compile and execute with CodeNo being set to 0?

Jon Skeet
people
quotationmark

It's compiling because you haven't got Option Strict on. If you turn on Option Strict (which IMO you should pretty much always do) it won't compile - your function isn't compatible with either ThreadStart or ParameterizedThreadStart. If you change the parameter type to Object however, it's fine - and you can a value into Start which will then be passed to the function. Short but complete example:

Option Strict On

Imports System
Imports System.Threading

Public Class Test
    Public Shared Sub Main()
        Dim thread As New Thread(AddressOf Foo)
        thread.Start("hello")
        thread.Join()
    End Sub

    Private Shared Sub Foo(ByVal value As Object)
        Console.WriteLine(value)
    End Sub
End Class

people

See more on this question at Stackoverflow