|
Knowing when to use Subs and Functions (VB.Net) |
|
|
Written by: Justin Rich
Knowing when to use Subs and FunctionsContent: Differences between Subs & Functions and when to use which one.
Having both Subs and Functions is something that is pretty unique to VB because of the history of VB programming. Visual Basic has been around since the early 1990's and from the beginning, we were provided with these "Subroutines" that enabled us to break up our code in to more manageable parts. "Functions" do the same thing, so most people are perplexed as to what Subs are for. First lets look at the use in VB.Net:
Private Sub doThis() 'do work here End Sub
Private Function doThat() as Boolean 'do work & return Boolean result Return True End Sub
These both can be called from the program by simply calling doThis() or doThat() and they both accept parameters in the parenthesis. The purpose of the Function as seen above is that it can return a variable. This is done simply by typing Return and then the variable name. In the example above, I'm just returning a literal. You can make Subs work like functions by passing parameters to it by reference rather than by value and that enables the variable being passed to be changed by the Sub and be available to the calling Sub or Function without having to assign a return to a new or existing variable. This is done like this:
Private Sub doThis(ByRef strVar as String) 'do manipulation on strVar here End Sub
Any manipulation to the variable passed to the Sub will be visible in the calling Sub or Function whereas in a Function you have to actually assign the variable to Function call:
Private Sub main() Dim strExisting as String = "Test" Dim strNew as String = doThat(strExisting) End Sub
Private Function doThat(ByVal strIn as String) strIn &= " 123" Return strIn End Function
In this case, the strExisting variable is unchanged, but strNew is now "Test 123". You can pass by reference to Functions as well, so the same functionality exists in both, but you just can't return from a Sub... reference is the only way to get values out of a Sub. Subs are usually used to do something that doesn't require a return and would be the equivilent to a 'return void;' in C derivatives. I personally don't use Subs that often because I like to at least return boolean true or false for successful completion of the task I'm demanding from the program. For that, read my article about the Try Catch statements. |
|
|
|
|
|