VB.NET Recursion Explanation

The VB.NET programming language

You want to see an example of recursion in the VB.NET programming language. A recursive function is one that calls itself. Recursive functions need special stop conditions; otherwise they will continue calling themselves infinitely. With the ByRef keyword, we can provide a way to stop a recursive function.

This VB tutorial shows how to develop and call recursive Functions.

Example

The Recursive() Function shown here receives two arguments. The first argument is a value that is doubled on each call. The second argument is received ByRef, which means it exists in one memory place and it is incremented on every function invocation. The count represents the total number of times the Function has been called, no matter the calling pattern.

Program that uses recursive method [C#]

Module Module1

    Function Recursive(ByVal value As Integer, ByRef count As Integer) As Integer
	Console.WriteLine("Recursive({0}, {1})", value, count)

	count = count + 1
	If value >= 100 Then
	    Return value
	End If
	Return Recursive(value * 2, count)
    End Function

    Sub Main()
	Dim count As Integer = 0
	Dim total As Integer = Recursive(5, count)

	Console.WriteLine("Total = {0}", total)
	Console.WriteLine("Count = {0}", count)
    End Sub

End Module

Output

Recursive(5, 0)
Recursive(10, 1)
Recursive(20, 2)
Recursive(40, 3)
Recursive(80, 4)
Recursive(160, 5)
Total = 160
Count = 6

Output. Let's examine the output of the program. We see that the Recursive function is called six times. After 5 is multiplied by 2 five times, we have the result 160. On the sixth function call, the multiplication does not occur.

ByRef

ByVal/ByRef operators in VB.NET

What is the importance of ByRef when making recursive method calls? Let's say you want to terminate an algorithm after 1000 method calls. If you use ByRef, this is possible no matter the calling order of the functions. If you don't use ByRef, you cannot terminate the algorithm in this way, because the arguments will be copied to further calls without being changed by previous calls from the same function.

Tip: You could always just use a shared variable. This is inelegant but really just as good in most program contexts.

Summary

Recursion is a fascinating and important topic in computer science. This glimpse of recursion in VB.NET is not comprehensive, but the usage of ByRef in recursive algorithms is useful. Recursion can be always rewritten as iteration, which is often more efficient. In critical programs, iteration is typically more reliable and easy to debug, and thus preferred.

VB.NET Tutorials
.NET