VB.NET Subroutines - Procedures in Visual Basic 2008
A subroutine is a block of statements that carries out a well-defined task. The block of statements is placed within a set of Sub. . .End Sub statements and can be invoked by name.
The following subroutine displays the current date in a message box and can be called by its name, ShowDate():
Normally, the task performed by a subroutine is more complicated than this; but even this simple subroutine is a block of code isolated from the rest of the application. The statements in a subroutine are executed, and when the End Sub statement is reached, control returns to the calling program. It's possible to exit a subroutine prematurely by using the Exit Sub statement.
All variables declared within a subroutine are local to that subroutine. When the subroutine exits, all variables declared in it cease to exist.
Most procedures also accept and act upon arguments. The ShowDate() subroutine displays the current date in a message box. If you want to display any other date, you have to implement it differently and add an argument to the subroutine:
birthDate is a variable that holds the date to be displayed; its type is Date. The ByVal keyword means that the subroutine sees a copy of the variable, not the variable itself. What this means practically is that the subroutine can't change the value of the variable passed by the calling application. To display the current date in a message box, you must call the ShowDate() subroutine as follows from within your program:
To display any other date with the second implementation of the subroutine, use a statement like the following:
Or, you can pass the value to be displayed directly without the use of an intermediate variable:
If you later decide to change the format of the date, there's only one place in your code you must edit: the statement that displays the date from within the ShowDate() subroutine.
Table of Contents
W3computing.com Copyright 2011 © All Rights Reserved