5

Is there a way in vb.net to create a sub/function that will take as an argument some kind of pointer to another function, and allow this new sub/function to execute the passed function?

What I have are 10-12 xml-rpc functions I am calling against a remote server. Each of these functions has different argument lists (one takes 1 string, another might take 3 strings and one int, etc). All of them return an object.

As I am calling these, it seems like it should be able to be factored better. For instance, everytime I call any of these functions, I want to test the return value for a session drop, and do something to try and reconnect to the remote system, etc.

Using .net 3.5

Thanks!

-R

Michael Shimmins
  • 19,961
  • 7
  • 57
  • 90
rob
  • 63
  • 1
  • 1
  • 4

4 Answers4

16

You need to be taken...to Func'y town

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Pierreten
  • 9,917
  • 6
  • 37
  • 45
4
Public Sub DoSomething(outerFunction as Func(of T))
    ' do something

    ' call passed in function
    Dim value = outerFunction
End Sub
Michael Shimmins
  • 19,961
  • 7
  • 57
  • 90
3

Use Func<in T, out TResult>

Braiam
  • 1
  • 11
  • 47
  • 78
Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
  • I edited your answer to make it clearer to other people [reviewing it](http://stackoverflow.com/review/low-quality-posts/11760430) in the review queue that it's not a link-only answer. – Wai Ha Lee Mar 24 '16 at 16:11
  • FWIW, I think that the pun in [the answer that came after yours](http://stackoverflow.com/a/2734209/1364007) which has functionally the same contents probably doesn't warrant the extra 11 upvotes it gets over yours. – Wai Ha Lee Mar 24 '16 at 16:26
1

After some more research, I came up with a solution:

Using the CallByName function:

MSDN reference

This allowed me to have one function that actually ran the 12 individual functions, and enabled me to have a centralized error handling system:

   Private Function RunRemoteRequest(ByVal functionName As String, ByVal service_url As String, ByVal args() As Object) As Object
    Dim retnVal As Object

    Dim success As Boolean = False
    While success = False And Me._connAttemptCount < MAX_ATTEMPTS
        Try
            retnVal = CallByName(remProxy, functionName, Method, args)
            success = True
            Me._connAttemptCount = 0
        Catch ex As Exception
            Me._connAttemptCount += 1
            If ex.Message = "Error I am looking for" Then
                Me.Login()
            Else
                log.Error("Error in RunRemoteRequest(" & functionName & ").", ex)
            End If
        End Try
    End While

    RunRemoteRequest = retnVal

End Function 

Note that you need to have Imports Microsoft.VisualBasic.CallType in the module/class you are working on.

rob
  • 63
  • 1
  • 1
  • 4