Home

Introduction to Procedures

 

Introduction to Procedures

 

Procedures

One of the techniques used for effective programming is to divide a big assignment in (relatively small) sub-assignments. Each sub-assignment is meant to (possibly completely) solve a particular problem so that other sub-assignments of the program can simply request its result or refer to it when necessary. Such a sub-assignment is called a procedure. There are two categories of procedures you will use in your programs: those that have already been created thus made available to you, and those you will create yourself.

Some languages like Visual Basic and Pascal consider that there are two types of procedures: sub routines and functions (some other languages like C++ and C# don't explicitly differentiate both categories).

 

Practical Learning: Introducing Procedures

  1. Start Microsoft Visual Studio .NET and create a new Visual Basic ASP.NET Application named http://localhost/GCS1
  2. In the Solution Explorer, right-click WebForm1.aspx and click Rename
  3. Type cleaningorder.aspx and press Enter
  4. Design the form as follows (you can find its HTML code here):
      
    Control ID Text Other Properties
    Label   Georgetown Cleaning Services  
    Label   Cleaning Order  
    Label   ________________________________  
    TextBox txtCustomerName    
    TextBox txtCustomerPhone    
    TextBox txtDateLeft    
    TextBox txtTimeLeft    
    TextBox txtDateExpected    
    TextBox txtTimeExpected    
    Label   ________________________________  
    TextBox txtShirtsUnitPrice 1.25  
    TextBox txtShirtsQty 0  
    TextBox txtShirtsSubTotal 0.00  
    Button btnCalculate Calculate  
    TextBox txtPantsUnitprice 2.75  
    TextBox txtPantsQty 0  
    TextBox txtPantsSubTotal 0.00  
    TextBox txtCleaningTotal 0.00  
    DropDownList cboItem1   Items: None, Women Suit, Dress, Regular Skirt, Skirt With Hook, Men's Suit 2Pc, Men's Suit 3Pc, Sweater, Tie, Coat, Jacket, Swede
    TextBox txtItem1Unitprice 0.00  
    TextBox txtItem1Qty 0  
    TextBox txtItem1SubTotal 0.00  
    TextBox txtTaxRate 5.75  
    DropDownList cboItem2   Items: None, Women Suit, Dress, Regular Skirt, Skirt With Hook, Men's Suit 2Pc, Men's Suit 3Pc, Sweater, Tie, Coat, Jacket, Swede
    TextBox txtTaxAmount 0.00  
    TextBox txtItem2Unitprice 0.00  
    TextBox txtItem2Qty 0  
    TextBox txtItem2SubTotal 0.00  
    DropDownList cboItem3   Items: None, Women Suit, Dress, Regular Skirt, Skirt With Hook, Men's Suit 2Pc, Men's Suit 3Pc, Sweater, Tie, Coat, Jacket, Swede
    TextBox txtItem3Unitprice 0.00  
    TextBox txtItem3Qty 0  
    TextBox txtItem3SubTotal 0.00  
    TextBox txtOrderTotal 0.00  
    DropDownList cboItem4   Items: None, Women Suit, Dress, Regular Skirt, Skirt With Hook, Men's Suit 2Pc, Men's Suit 3Pc, Sweater, Tie, Coat, Jacket, Swede
    TextBox txtItem4Unitprice 0.00  
    TextBox txtItem4Qty 0  
    TextBox txtItem4SubTotal 0.00  
    Button btnStartOver Start Over  
    Label   ________________________________  
  5. Execute the application to preview the form
  6. After viewing the browser, close it and return to your programming environment

Introduction to Sub-Procedures

A sub procedure is an assignment that is carried but doesn't give back a result. To create a sub procedure, you start the section of code with the Sub keyword followed by a name (like everything else, a procedure must have a name). The name of a procedure is always followed by parentheses. At the end of the sub procedure, you must type End Sub. Therefore, the formula of a sub procedure is:

Sub ProcedureName()

End Sub

The name of a procedure follows the same rules we reviewed for variables. In addition, there are some suggestions you can use when naming your procedures:

  • If the procedure performs an action that can be represented with a verb, you can use that verb to name it. Here are examples: show, display
  • To make the name of a procedure stand, you should start it in uppercase. Examples are Show, Play, Dispose, Close
  • You should use explicit names that identify the purpose of the procedure. If a procedure would be used as a result of another procedure, reflect it on the name of the sub procedure. Examples would be: afterupdate, longbefore.
  • If the name of a procedure is a combination of words, you should start each word in uppercase. Examples are: AfterUpdate, SayItLoud

The section between the Sub and the End Sub lines is referred to as the body of the procedure. Here is an example:

Sub Assignment()

End Sub

The body of the procedure is used to define what, and how, the assignment should be carried. For example, if you need to use a variable, you can declare it and specify the kind of variable you need. There is no restriction on the type of variables that can be declared in a procedure. Here is an example in which a string variable is declared in the body of a sub routine:

Sub Assignment()
    Dim strFullName As String
End Sub

In the same way, you can declare as many variables as you need inside of a procedure. The actions you perform inside of a procedure depend on what you are trying to accomplish. For example, a procedure can simply be used to create a string. The above procedure can be changed as follows:

Sub Assignment()
    Dim strFullName As String
    strFullName = "Paul Bertrand Yamaguchi"
End Sub
 

Practical Learning: Creating a Sub Procedure

  1. Right-click anywhere in the form and click View Code
  2. To create the procedures that calculate the sub-total of each item, type the following:
     
    Private Sub CalculateShirts()
            Dim UnitPrice As Double
            Dim Quantity As Integer
            Dim SubTotal As Double
    
            ' Get the unit price of the item
            UnitPrice = CDbl(txtShirtsUnitPrice.Text)
    
            ' If the user forgot to enter a valid quantity, consider it 0
            If txtShirtsQty.Text = "" Then
                Quantity = 0
            Else
                Quantity = CInt(txtShirtsQty.Text)
            End If
    
            ' Once you have the unit price and the quantity, calculate the sub-total
            SubTotal = UnitPrice * Quantity
            ' After calculating the sub-total, display it in the corresponding text box
            txtShirtsSubTotal.Text = SubTotal.ToString("F")
        End Sub
        Private Sub CalculatePants()
            Dim UnitPrice As Double
            Dim Quantity As Integer
            Dim SubTotal As Double
    
            UnitPrice = CDbl(txtPantsUnitPrice.Text)
    
            If txtPantsQty.Text = "" Then
                Quantity = 0
            Else
                Quantity = CInt(txtPantsQty.Text)
            End If
    
            SubTotal = UnitPrice * Quantity
            txtPantsSubTotal.Text = SubTotal.ToString("F")
        End Sub
        Private Sub CalculateItem1()
            Dim UnitPrice As Double
            Dim Quantity As Integer
            Dim SubTotal As Double
    
            UnitPrice = CDbl(txtItem1UnitPrice.Text)
    
            If txtItem1Qty.Text = "" Then
                Quantity = 0
            Else
                Quantity = CInt(txtItem1Qty.Text)
            End If
    
            ' Make sure that the user has specified the item to clean, not "None"
            If cboItem1.SelectedIndex = 1 Then
                txtItem1SubTotal.Text = "0.00"
            Else
                SubTotal = UnitPrice * Quantity
                txtItem1SubTotal.Text = SubTotal.ToString("F")
            End If
        End Sub
        Private Sub CalculateItem2()
            Dim UnitPrice As Double
            Dim Quantity As Integer
            Dim SubTotal As Double
    
            UnitPrice = CDbl(txtItem2UnitPrice.Text)
    
            If txtItem2Qty.Text = "" Then
                Quantity = 0
            Else
                Quantity = CInt(txtItem2Qty.Text)
            End If
    
            If cboItem2.SelectedIndex = 1 Then
                txtItem2SubTotal.Text = "0.00"
            Else
                SubTotal = UnitPrice * Quantity
                txtItem2SubTotal.Text = SubTotal.ToString("F")
            End If
        End Sub
        Private Sub CalculateItem3()
            Dim UnitPrice As Double
            Dim Quantity As Integer
            Dim SubTotal As Double
    
            UnitPrice = CDbl(txtItem3UnitPrice.Text)
    
            If txtItem3Qty.Text = "" Then
                Quantity = 0
            Else
                Quantity = CInt(txtItem3Qty.Text)
            End If
    
            If cboItem3.SelectedIndex = 1 Then
                txtItem3SubTotal.Text = "0.00"
            Else
                SubTotal = UnitPrice * Quantity
                txtItem3SubTotal.Text = SubTotal.ToString("F")
            End If
        End Sub
        Private Sub CalculateItem4()
            Dim UnitPrice As Double
            Dim Quantity As Integer
            Dim SubTotal As Double
    
            UnitPrice = CDbl(txtItem4UnitPrice.Text)
    
            If txtItem4Qty.Text = "" Then
                Quantity = 0
            Else
                Quantity = CInt(txtItem4Qty.Text)
            End If
    
            If cboItem4.SelectedIndex = 1 Then
                txtItem4SubTotal.Text = "0.00"
            Else
                SubTotal = UnitPrice * Quantity
                txtItem4SubTotal.Text = SubTotal.ToString("F")
            End If
        End Sub
  3. Return to the form

Calling a Sub Procedure

Once you have a procedure, whether you created it or it is part of the Visual Basic language, you can use it. Using a procedure is also referred to as calling it. Before calling a procedure, you should first locate the section of code in which you want to use it. To call a simple procedure, simply type its name in the section where you want to use followed by (empty, for now) parentheses. For example, you can call the assignment in the Load event of a form as follows:

Sub Caller()
    Assignment()
End Sub
 

Practical Learning: Calling a Sub Procedure

  1. On the form, double-click the Calculate button and implement its event as follows:
      
    Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
            Dim Shirts As Double
            Dim Pants As Double
            Dim Item1 As Double
            Dim Item2 As Double
            Dim Item3 As Double
            Dim Item4 As Double
            Dim CleaningTotal As Double
            Dim TaxRate As Double
            Dim TaxAmount As Double
            Dim OrderTotal As Double
    
            ' Call each procedure that calculates an item
            CalculateShirts()
            CalculatePants()
            CalculateItem1()
            CalculateItem2()
            CalculateItem3()
            CalculateItem4()
    
            ' Retrieve the sub-total of each item
            Shirts = CDbl(txtShirtsSubTotal.Text)
            Pants = CDbl(txtPantsSubTotal.Text)
            Item1 = CDbl(txtItem1SubTotal.Text)
            Item2 = CDbl(txtItem2SubTotal.Text)
            Item3 = CDbl(txtItem3SubTotal.Text)
            Item4 = CDbl(txtItem4SubTotal.Text)
    
            ' Calculate the total of the cleaning
            CleaningTotal = Shirts + Pants + Item1 + Item2 + Item3 + Item4
            ' Take care of Uncle Sam
            TaxRate = CDbl(txtTaxRate.Text)
            TaxAmount = CleaningTotal * TaxRate / 100
            ' Add the cleaning total to the tax to get the net price
            OrderTotal = CleaningTotal + TaxAmount
    
            ' Display the values in the corresponding text boxes
            txtCleaningTotal.Text = CleaningTotal.ToString("F")
            txtTaxAmount.Text = TaxAmount.ToString("F")
            txtOrderTotal.Text = OrderTotal.ToString("F")
        End Sub
  2. In the Class Name combo box, select btnStartOver
  3. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnStartOver_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnStartOver.Click
            txtCustomerName.Text = ""
            txtCustomerPhone.Text = ""
            txtDateLeft.Text = ""
            txtTimeLeft.Text = ""
            txtDateExpected.Text = ""
            txtTimeExpected.Text = ""
            txtShirtsQty.Text = "0"
            txtShirtsSubTotal.Text = "0.00"
            txtPantsQty.Text = "0"
            txtPantsSubTotal.Text = "0.00"
            cboItem1.SelectedIndex = 0
            txtItem1UnitPrice.Text = "0.00"
            txtItem1Qty.Text = "0"
            txtItem1SubTotal.Text = "0.00"
            cboItem2.SelectedIndex = 0
            txtItem2UnitPrice.Text = "0.00"
            txtItem2Qty.Text = "0"
            txtItem2SubTotal.Text = "0.00"
            cboItem3.SelectedIndex = 0
            txtItem3UnitPrice.Text = "0.00"
            txtItem3Qty.Text = "0"
            txtItem3SubTotal.Text = "0.00"
            cboItem4.SelectedIndex = 0
            txtItem4UnitPrice.Text = "0.00"
            txtItem4Qty.Text = "0"
            txtItem4SubTotal.Text = "0.00"
            txtCleaningTotal.Text = "0.00"
            txtTaxRate.Text = "5.75"
            txtTaxAmount.Text = "0.00"
            txtOrderTotal.Text = "0.00"
    End Sub
  4. Execute the application and process a few orders. Here is an example 
     
  5. Close the form and return to MSVB

Functions

 

Introduction

Like a sub procedure , a function is used to perform an assignment. The main difference between a sub procedure and a function is that, after carrying its assignment, a function gives back a result. We also say that a function "returns a value". To distinguish both, there is a different syntax you use for a function.

 

Practical Learning: Introducing Functions

  1. Start a new Visual Basic ASP.NET Application named http://localhost/geometry1
  2. Save the following picture in the folder that contains the current project (it should be Drive:\Inetpub\wwwroot\geometry1)
    (When designing the form, in the cell of the table where the figure should be shown, you will set its code to <img src="box1.gif">)
     
  3. In the Solution Explorer, right-click WebForm1.aspx and click Rename
  4. Type box.aspx and press Enter
  5. Design the form as follows (you can find its HTML code here):
      
    Control ID Text Other Properties
    Label   Geometric Figures  
    Label   Rectangular Parrallelepiped  
    TextBox txtLength 0.00  
    TextBox txtHeight 0.00  
    TextBox txtWidth 0.00  
    Button btnProcess Process Figure  
    TextBox txtFBPerimeter 0.00  
    TextBox txtFBArea 0.00  
    TextBox txtTBPerimeter 0.00  
    TextBox txtLFPerimeter 0.00  
    TextBox txtLFArea 0.00  
    TextBox txtTotalArea 0.00  
    TextBox txtVolume 0.00  
  6. Execute the application to preview the form
  7. After viewing the browser, close it and return to your programming environment
 

Function Creation

To create a function, you use the Function keyword followed by a name and parentheses. Unlike a sub procedure, because a function returns a value, you should/must specify the type of value the function will produce. To give this information, on the right side of the closing parentheses, you can type the As keyword, followed by a data type. To indicate where a function stops, type End Function. Based on this, the basic formula used to create a function is:

Function FunctionName() As DataType
    
End Function

The name of a function follows the same rules and suggestions we reviewed for sub procedures. The DataType factor indicates the type of value that the function will return. If the function will produce a word or a group of words, you can create it as String. If the function will check something and determine whether it produces a true or a false value, you can create it as Boolean. The other data types are also valid in the contexts we reviewed them. Here is an example:

Function GetFullName() As String
        
End Function

As done with the variables, you can also use a type character as the return type of a function and omit the As DataType expression. The type character is typed on the right side of the function name and before the opening parenthesis. An example would be GetFullname$(). As with the variables, you must use the appropriate character for the function:

Character The function must return
& a String type
% a Byte, Short, Int16, or In32
& an Int64 or a Long
! a Single type
# a Double
@ a Decimal

Here is an example:

Function GetFullName$()
        
End Function

As mentioned already, the section between the Function and the End Function lines is the body of the function. It is used to describe what the function does. As done on a sub procedure, one of the actions you can perform in a function is to declare a (local) variable and use it as you see fit. Here is an example:

Function CallMe() As String
    Dim Salute As String
    Salute = "You can call me Al"
End Function

After performing an assignment in a function, to indicate the value it returns, somewhere after the assignment and before the End Function line, type the name of the function, followed by the assignment operator "=", followed by the value the function returns. Here is an example in which a function returns a name:

Function GetFullName$()
        Dim FirstName, LastName As String

        FirstName = "Jenny"
        LastName = "McArthy"

        GetFullName = LastName & ", " & FirstName
End Function

You can also use the Return keyword to specify the returned value of a function. Here is an example in which a function returns a name:

Function GetFullName$()
        Dim FirstName, LastName As String

        FirstName = "Jenny"
        LastName = "McArthy"

        Return (LastName & ", " & FirstName)
End Function

You can also use some local variables in the function to perform an assignment and then assign their result to the name of the function.

Practical Learning: Creating Functions

  1. Right-click anywhere in the form and click View Code
  2. To create a few functions, type the following code above the End Class line:
     
    Function CalculateFacePerimeter() As Double
            Dim Length As Double
            Dim Height As Double
            Dim Perimeter As Double
    
            Length = CDbl(txtLength.Text)
            If Length < 0 Then CalculateFacePerimeter = 0
    
            Height = CDbl(txtHeight.Text)
            If Height < 0 Then CalculateFacePerimeter = 0
    
            Perimeter = (Length + Height) * 2
            CalculateFacePerimeter = Perimeter
        End Function
    
        Function CalculateTopPerimeter#()
            Dim Length As Double
            Dim Width As Double
            Dim Perimeter As Double
    
            Length = CDbl(txtLength.Text)
            If Length < 0 Then Return 0
    
            Width = CDbl(txtWidth.Text)
            If Width < 0 Then Return 0
    
            Perimeter = (Length + Width) * 2
            CalculateTopPerimeter = Perimeter
        End Function
        Function CalculateSidePerimeter() As Double
            Dim Height#
            Dim Width#
    
            Height = CDbl(txtHeight.Text)
            If Height < 0 Then Return 0
    
            Width = CDbl(txtWidth.Text)
            If Width < 0 Then Return 0
    
            Return (Width + Height) * 2
        End Function
    
        Function CalculateVolume#()
            Dim Length As Double
            Dim Height#
            Dim Width As Double
    
            Length = CDbl(txtLength.Text)
            Height = CDbl(txtHeight.Text)
            Width = CDbl(txtWidth.Text)
    
            CalculateVolume = Length * Height * Width
        End Function
    
    End Class
  3. Save all

Calling a Function

As done for the sub procedure, in order to use a function in your program, you must call it. Like a sub procedure, to call a function, you can simply type its name in the desired section of the program. Here is an example:

Sub Caller()
    CallMe
End Sub

Since the primary purpose of a function is to return a value, to better take advantage of such a value, you can assign the name of a function to a property or a variable in the section where you are calling the function. Here is an example:

Function GetFullName$()
        Dim FirstName, LastName As String

        FirstName = "Jenny"
        LastName = "McArthy"

        GetFullName = LastName & ", " & FirstName
End Function

Sub Caller()
        Dim FullName As String

        FullName = GetFullName()

End Sub
 
 

Practical Learning: Calling a Function

  1. To call the functions created earlier, create the following procedure above the End Class line:
     
    Sub CalculateTotalPerimeter()
            Dim PerimeterFace As Double
            Dim PerimeterTop As Double
            Dim PerimeterSide As Double
    
            PerimeterFace = CalculateFacePerimeter()
            PerimeterTop = CalculateTopPerimeter()
            PerimeterSide = CalculateSidePerimeter()
    
            txtFBPerimeter.Text = CStr(PerimeterFace)
            txtTBPerimeter.Text = CStr(PerimeterTop)
            txtLRPerimeter.Text = CStr(PerimeterSide)
    End Sub
    
    End Class
  2. To complete the code, create the following procedure just above the End Class line
      
    Sub ProcessTotalArea()
            Dim Length#, Height#, Width#
            Dim AreaFace#, AreaTop#, AreaSide#, TotalArea#
    
            Length = CDbl(txtLength.Text)
            Height = CDbl(txtHeight.Text)
            Width = CDbl(txtWidth.Text)
    
            AreaFace = Length * Height
            AreaTop = Length * Width
            AreaSide = Height * Width
            TotalArea = (2 * AreaFace) + (2 * AreaTop) + (2 * AreaSide)
    
            txtFBArea.Text = CStr(AreaFace)
            txtTBArea.Text = CStr(AreaTop)
            txtLRArea.Text = CStr(AreaSide)
            txtTotalArea.Text = CStr(TotalArea)
        End Sub
    
    End Class
  3. In the Class Name combo box, select btnProcess
  4. In the Method Name combo box, select Click
  5. To further call another function, implement the event as follows:
     
    Function CalculateFacePerimeter() As Double
            Dim Length As Double
            Dim Height As Double
            Dim Perimeter As Double
    
            Length = CDbl(txtLength.Text)
            If Length < 0 Then CalculateFacePerimeter = 0
    
            Height = CDbl(txtHeight.Text)
            If Height < 0 Then CalculateFacePerimeter = 0
    
            Perimeter = (Length + Height) * 2
            CalculateFacePerimeter = Perimeter
        End Function
    
        Function CalculateTopPerimeter#()
            Dim Length As Double
            Dim Width As Double
            Dim Perimeter As Double
    
            Length = CDbl(txtLength.Text)
            If Length < 0 Then Return 0
    
            Width = CDbl(txtWidth.Text)
            If Width < 0 Then Return 0
    
            Perimeter = (Length + Width) * 2
            CalculateTopPerimeter = Perimeter
        End Function
        Function CalculateSidePerimeter() As Double
            Dim Height#
            Dim Width#
    
            Height = CDbl(txtHeight.Text)
            If Height < 0 Then Return 0
    
            Width = CDbl(txtWidth.Text)
            If Width < 0 Then Return 0
    
            Return (Width + Height) * 2
        End Function
    
        Function CalculateVolume#()
            Dim Length As Double
            Dim Height#
            Dim Width As Double
    
            Length = CDbl(txtLength.Text)
            Height = CDbl(txtHeight.Text)
            Width = CDbl(txtWidth.Text)
    
            CalculateVolume = Length * Height * Width
        End Function
        Sub CalculateTotalPerimeter()
            Dim PerimeterFace As Double
            Dim PerimeterTop As Double
            Dim PerimeterSide As Double
            Dim Total As Double
    
            PerimeterFace = CalculateFacePerimeter()
            PerimeterTop = CalculateTopPerimeter()
            PerimeterSide = CalculateSidePerimeter()
            Total = (2 * PerimeterFace) + (2 * PerimeterTop) + (2 * PerimeterSide)
    
            txtFBPerimeter.Text = CStr(PerimeterFace)
            txtTBPerimeter.Text = CStr(PerimeterTop)
            txtLRPerimeter.Text = CStr(PerimeterSide)
        End Sub
        Sub ProcessTotalArea()
            Dim Length#, Height#, Width#
            Dim AreaFace#, AreaTop#, AreaSide#, TotalArea#
    
            Length = CDbl(txtLength.Text)
            Height = CDbl(txtHeight.Text)
            Width = CDbl(txtWidth.Text)
    
            AreaFace = Length * Height
            AreaTop = Length * Width
            AreaSide = Height * Width
            TotalArea = (2 * AreaFace) + (2 * AreaTop) + (2 * AreaSide)
    
            txtFBArea.Text = CStr(AreaFace)
            txtTBArea.Text = CStr(AreaTop)
            txtLRArea.Text = CStr(AreaSide)
            txtTotalArea.Text = CStr(TotalArea)
        End Sub
    
        Private Sub btnProcess_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnProcess.Click
            CalculateTotalPerimeter()
            ProcessTotalArea()
            txtVolume.Text = CalculateVolume()
        End Sub
    End Class
  6. Execute the application and enter the values for the dimensions of a box before clicking the button. Here is an example:

Arguments and Parameters

 

Introduction

So far, to use a value in a procedure, we had to declare it. In some cases, a procedure may need an external value in order to carry its assignment. A value that is supplied to a procedure is called an argument.

When creating a procedure that will use an external value, declare the argument that represents that value between the parentheses of the procedure. For a sub routine, the formula you use would be:

Sub ProcedureName(Argument)
      
End Sub

If you are creating a function, the formula would be:

Function ProcedureName(Argument) As DataType
      
Function Sub

The argument must be declared as a normal variable, omitting the Dim keyword. Here is an example that creates a function that takes a string as argument:

Function CalculatePayroll(strName As String) As Double
      
Function Sub

A certain procedure can take more than one argument. In this case, in the parentheses of the procedure, separate the arguments with a comma. Here is an example of a sub routine that takes two arguments:

Sub EvaluateInvoice(EmplName As String, HourlySalary As Currency)
      
End Sub

In the body of a procedure that takes one or more arguments, use the argument(s) as you see fit as if they were locally declared variables. For example, you can involve them with values inside of the procedure. You can also exclusively use the values of the arguments to perform the assignment.

 

Passing Arguments (By Value)

To call a procedure that takes an argument, type its name and a space, followed by a value for each argument between parentheses. The value provided for an argument is also called a parameter. If there is more than one argument, separate them with a comma. Here is an example:

Function GetFullName$(strFirst As String, strLast As String)
        Dim FName As String

        FName = strFirst & " " & strLast
        GetFullName = FName
End Function

Sub Caller()
        Dim FirstName, LastName As String
        Dim FullName As String
        Dim ComputerLanguage As String = "VBasic"

        FirstName = "John"
        LastName = "Glasgow"

        FullName = GetFullName(FirstName, LastName)
End Sub

Alternatively, you can use the Call keyword to call a procedure. Here is an example:

Sub Caller()
        Call Welcome(ComputerLanguage)
End Sub

When you call a procedure that takes more than one argument, you must provide the values of the arguments in the order they are listed inside of the parentheses of the procedure. There is an exception. If you know the names of the arguments, you can type them in any order and provide a value for each. To do that, on the right side of each argument, type the := operator followed by the desired value for the argument. Here is an example:

Function GetFullName$(MI As String, LastName As String, FirstName As String)
        GetFullName = FirstName & " " & MI & " " & LastName
End Function

Sub Caller()
        Dim FullName As String
        Dim ComputerLanguage As String = "VBasic"

        FullName = GetFullName(LastName:="Roberts", FirstName:="Alan", MI:="R.")
End Sub

When calling a procedure that takes an argument, we were supplying a value for that argument. When this is done, the procedure that is called makes a copy of the value of the argument and makes that copy available to the calling procedure. That way, the argument itself is not accessed. This is referred to as passing an argument by value. This is reinforced by typing the ByVal keyword on the left side of the argument. Here is an example:

Sub Welcome(ByVal strLanguage As String)

End Sub
 

Practical Learning: Passing Arguments by Value

  1. To pass arguments by value, change the functions and procedures as follows In fact, change the whole file as follows):
     
    Function CalculatePerimeter(ByVal Side1 As Double, ByVal Side2 As Double) As Double
            Dim Perimeter As Double
    
            If Side1 < 0 Then Return 0
            If Side2 < 0 Then Return 0
    
            Perimeter = (Side1 + Side2) * 2
            CalculatePerimeter = Perimeter
    End Function
    Function CalculateArea#(ByVal Side1 As Double, ByVal Side2 As Double)
            Dim Area#
    
            If Side1 < 0 Then Return 0
            If Side2 < 0 Then Return 0
    
            Area = Side1 * Side2
            Return Area
    End Function
    
    Function CalculateVolume#(ByVal Side1#, ByVal Side2#, ByVal Side3#)
            CalculateVolume = Side1 * Side2 * Side3
    End Function
    
    Private Sub btnProcess_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnProcess.Click
            Dim Length As Double
            Dim Height As Double
            Dim Width As Double
            Dim PerimeterFace As Double
            Dim PerimeterTop As Double
            Dim PerimeterSide As Double
            Dim TotalPerimeter As Double
            Dim AreaFace#, AreaTop#, AreaSide#, TotalArea#
            Dim Volume As Double
    
            Length = CDbl(txtLength.Text)
            Height = CDbl(txtHeight.Text)
            Width = CDbl(txtWidth.Text)
    
            PerimeterFace = CalculatePerimeter(Length, Height)
            PerimeterTop = CalculatePerimeter(Length, Width)
            PerimeterSide = CalculatePerimeter(Height, Width)
    
            txtFBPerimeter.Text = CStr(PerimeterFace)
            txtTBPerimeter.Text = CStr(PerimeterTop)
            txtLRPerimeter.Text = CStr(PerimeterSide)
    
            AreaFace = CalculateArea(Length, Height)
            AreaTop = CalculateArea(Length, Width)
            AreaSide = CalculateArea(Height, Width)
    
            txtFBArea.Text = CStr(AreaFace)
            txtTBArea.Text = CStr(AreaTop)
            txtLRArea.Text = CStr(AreaSide)
    
            TotalArea = (2 * AreaFace) + (2 * AreaTop) + (2 * AreaSide)
            txtTotalArea.Text = CStr(TotalArea)
    
            Volume = CalculateVolume(Length, Height, Width)
            txtVolume.Text = CStr(Volume)
    End Sub
    End Class
  2. Execute the application and test it with new values before clicking the button  
  3. Close the browser and return to your programming environment
 

Passing Arguments By Reference

An alternative to passing arguments as done so far is to pass the address of the argument to the called procedure. When this is done, the called procedure doesn't receive a simple copy of the value of the argument: the argument is accessed at its root. That is, at its memory address. With this technique, any action carried on the argument will be kept. If the value of the argument is modified, the argument would now have the new value, dismissing or losing the original value it had. This technique is referred to as passing an argument by reference. Consider the following program:

Function Addition#(ByVal Value1 As Double, ByVal Value2 As Double)
        Value1 = 24.55
        Value2 = 16.52

        Addition = Value1 + Value2
End Function

Sub Caller()
        Dim Result As String
        Dim Number1, Number2 As Double

        Result = Addition(Number1, Number2)    
End Sub

Notice that, although the values of the arguments were changed in Addition() procedure, at the end of the procedure, they lose the value they got in the function. If you want a procedure to change the value of an argument, you can pass the argument by reference. To pass an argument by reference, on its left, type the ByRef keyword. This is done only when creating the procedure. When the called procedure finishes with the argument, the argument would keep whatever modification was made on its value. 

 

Previous Copyright © 2005-2007 FunctionX, Inc. Next