Visual Basic.NET 2008 > Programming Fundamentals

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():

Sub ShowDate()
MsgBox(Now().ToShortDateString)
End Sub

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:

Sub ShowDate(ByVal birthDate As Date)
MsgBox(birthDate.ToShortDateString)
End Sub

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:

ShowDate()

To display any other date with the second implementation of the subroutine, use a statement like the following:

Dim myBirthDate = #2/9/1960#
ShowDate(myBirthDate)

Or, you can pass the value to be displayed directly without the use of an intermediate variable:

ShowDate(#2/9/1960#)

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
 
  Home | Useful links | Contact us