Using AddressOf... as a parameter

A

Anthony Coelho

Hello Guru's!

I am trying to pass a function pointer as a parameter to a method and can't
seem to get it working. Basically I want to do the exact same thing that the
System.Threading.Thread constructor does in VB.NET within my own class. In
the Thread constructor, you can specify the function to run instead of
creating a ThreadStart object by using the AddressOf keyword such as; Dim
oThread As New Threading.Thread(AddressOf foo.Run)

I have a method that I would like to do the exact same thing as, but what do
you declare the type as? I've tried a delegate, but that's not working for
me. For example, say you have the following method:

Public foo(mydelegate as System.Delegate)

If you call this method passing a function pointer such as
myClass.foo(AddressOf myfunction.DoSomething) you get the following error:

'AddressOf' expression cannot be converted to 'System.Delegate' because
'System.Delegate' is not a delegate type.

How's that for a error? System.Delegate is not a delegate type? Are you as
confused on this as I am? So to wrap, does anyone know how I can pass a
function pointer into a method as a parameter just like the Threading.Thread
constructor allows?

Cheers,
Anthony
 
P

Patrick Steele [MVP]

Hello Guru's!

I am trying to pass a function pointer as a parameter to a method and can't
seem to get it working. Basically I want to do the exact same thing that the
System.Threading.Thread constructor does in VB.NET within my own class. In
the Thread constructor, you can specify the function to run instead of
creating a ThreadStart object by using the AddressOf keyword such as; Dim
oThread As New Threading.Thread(AddressOf foo.Run)

I have a method that I would like to do the exact same thing as, but what do
you declare the type as? I've tried a delegate, but that's not working for
me.

First, define the delegate that matches the signature of what you want
to call:

Public Delegate Sub ShowStatusDelegate(newStatus As String)

This defines a delegate called "ShowStatusUpdate". It's signature is
basically:
1) A Sub
2) Accepts one string parameter

Now you need to define the actual procedure that you want pass via
AddressOf. It must match the signature above in your delegate (sub with
one string parameter)

Public Sub ShowStatus(data As String)
statusLable.Text = data
End Sub

Now, the method that accepts your 'AddressOf' parameter needs to accept
a type of "ShowStatusDelegate":

Public Sub foo(func As ShowStatusDelegate)
...
End Sub

Now you can call:

foo(AddressOf Me.ShowStatus)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top