Tuesday, July 10, 2007

Passing a Function by Reference in VB.NET

If you are creating Test code, it is often very useful to be able to pass a function by reference. In my example below, my test modules all have one parameter which is a pointer to a TestResult object. I pass my Test modules to the RunTest function which creates a TestResult object, populates certain fields, and passes the object to the test module (which was passed in as a reference). This allows all of the work done for each call to a test module to be consolidated into one nice and neat function.

The key to making this work is to define a delegate with the right parameter signature, then use the delegate's name (TestDelegate in my example) when defining the type for the function you are passing.

Example:

Public Class TestResult

Public name As String = ""
Public pass As Boolean = False
Public startTime As DateTime
Public endTime As DateTime
Public comments As String = ""

End Class

Public Delegate Sub TestDelegate(ByVal result As TestResult)



Private Sub RunTest(ByVal testFunction As TestDelegate)

Dim result As New TestResult
result.startTime = DateTime.Now
testFunction(result)
result.endTime = DateTime.Now

End Sub

Private Sub MenuItemStartTests_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MenuItemStartTests.Click

Debug.WriteLine("Starting Tests...")
Debug.WriteLine("")
'==================================

' Add Calls to Test Modules Here

RunTest(AddressOf Test1)
RunTest(AddressOf Test2)

'==================================


Debug.WriteLine("")
Debug.WriteLine("Tests Completed")

End Sub


Private Sub Test1(ByVal result As TestResult)

result.name = "Test #1"
.
.
.
result.pass = True

End Sub

Private Sub Test2(ByVal result As TestResult)

result.name = "Test #2"
.
.
.
result.pass = True

End Sub

4 comments:

Anonymous said...

Fantastic! Concise, easy to find and just what I needed. Thanks!

Anonymous said...

Thanks a Lot!
Solved my problem!

leorjgj - Brazil

Remo Harsono said...

Great! I search on Google with the keyword: vb.net parameter passing function

Then, this page is on top of the list. Quite easy to find...thanks

Anonymous said...

Thank's a lot, it's very helpful.
Said from Morocco