Topics
• Procedures
• Passing arguments to Procedures
• Functions • Debugging:
• Step into, over, and out of procedures and
Introduction
•
A
procedure
is a collection of statements that
performs a task
– Event handlers are a type of procedure
•
A
function
is a collection of statements that
performs a task
and
returns a value to the VB
statement that executed it
– Functions work like intrinsic functions, such as CInt
and IsNumeric
Procedures
A moderately complex program needs to perform multiple tasks.
A procedure is a block of program code that performs a specific task.
A program can be considered as the assembly of multiple procedures.
Execution of a procedure is commonly referred to as calling a procedure.
Most Visual Basic procedures are Sub procedures and Function
boss
worker2 worker3 worker1
worker4 worker5
How Procedure Works
A (called) procedure is invoked by another procedure (caller).
The called procedure does the job and return the result to the caller or simply transfer control to the caller without returning anything.
Sub Procedures vs. Function Procedures
A Sub procedure does not return a value after
performing its assigned task.
Sub Procedures
Two types of Sub procedures:
1. Event procedures
- Associated with a specific object and event
2. General Purpose Sub procedures
Sample Procedure, Tutorial 6-1
Sub DisplayMessage()
'A Sub procedure that displays a message. lstOutput.Items.Add("")
lstOutput.Items.Add("Hello from DisplayMessage procedure.") lstOutput.Items.Add("")
End Sub
Private Sub btnGo_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnGo.Click
' This procedure calls the DisplayMessage procedure.
lstOutput.Items.Add("Hello from btnGo_Click procedure.") lstOutput.Items.Add("Now I am calling the " & _
"DisplayMessage procedure." "procedure.") DisplayMessage()
Declaring a Procedure
• AccessSpecifier is optional and establishes
accessibility to the program
• Sub and End are keywords
• ProcedureName used to refer to procedure
– Use Pascal casing, capitalize 1st character of the name and
each new word in the name
• ParameterList is a list of variables or values being passed to the sub procedure. It is optional.
[AccessSpecifier] Sub ProcedureName ([ParameterList]) [Statements]
More on the Access Specifier
•
Private
allows use only from that form
•
Public
allows use from other forms
•
If not specified, default is Public
•
There are other access specifiers such as:
– Protected– Friend
– Protected Friend
Placing Sub Procedure in File
General Purpose Sub procedures can be placed anywhere in the Form's code module.
Sample Procedure
Private Sub DisplayGrade()
' Display the intAverage score.
lblAverage.Text = intAverage.ToString() ' Determine and display the letter grade. Select Case intAverage
Case 90 To 100
lblLetterGrade.Text = "A" Case 80 To 90
lblLetterGrade.Text = "B" Case 70 To 79
lblLetterGrade.Text = "C" Case 60 To 69
lblLetterGrade.Text = "D" Case Else
lblLetterGrade.Text = "E" End Select
Procedures and Static Variables
•
Variables needed only in a procedure, should
be declared
within
that procedure
– Creates a local variable with scope only within the procedure where declared
– Local variable values are not saved from one
procedure call to the next
•
To save value between procedure calls, use
Static
keyword to create a
static local variable
– Static VariableName As DataType
– Scope is still only within the procedure
Arguments
•
Argument
– a value passed to a procedure
•
We’ve already done this with functions
– Value = CInt(txtInput.Text)– Calls the CInt function and passes txtInput.Text as
an argument
•
A procedure must be declared with a parameter
Passing Multiple Arguments
• Multiple arguments separated by commas • Value of first argument is copied to first • Second to second, etc.
ShowSum(intValue1, intValue2) ' calls ShowSum procedure
Sub ShowSum(ByVal intNum1 As Integer, _
ByVal intNum2 As Integer)
' This procedure accepts two arguments, and prints ' their sum on the form.
Dim intSum As Integer
intSum = intNum1 + intNum2
Passing Variables
A variable has both a value and a unique address in the computer's memory. Either the value or the address can be passed to a Sub procedure.
Two ways of passing parameters:
(1) Pass by value. The value of the variable is passed to the called procedure;
Two analogies
Telling someone the balance of your banking account passes the information about your banking account. This is equivalent to "pass by value".
Giving someone the information on the account
Pass Variables by Value
Passing variables by value is specified in the parameter list.
Use the keyword ByVal in the variable declaration.
When the procedure is invoked, only the value of the variable is passed to the procedure.
Example:
Private Sub DisplayMessage(ByVal pet As String, ByVal years As String)
messageLabel.Text = "Your pet " & pet & " is " _ & years & " years old."
Pass Variables by Value (Cont'd)
In the calling procedure, you may have code like this:
Private Sub getInfoButton_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles
getInfoButton.Click
Dim petName As String Dim petAge As String
petName = InputBox("Pet's name:", "Name Entry") petAge = InputBox("Pet's age (years):", "Age Entry")
Passing Variables by Reference
•Passing variables by reference gives the receiving procedure access to the variable being passed.
•In most cases, you pass variables by reference when you want the receiving procedure to change the
contents of the variables.
Passing Variables by Reference (Cont'd)
Example
Private Sub calcButton_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles calcButton.Click
Dim hoursWkd As Decimal Dim rateOfPay As Decimal Dim grossPay As Decimal
hoursWkd =
Convert.ToDecimal(hoursListBox.SelectedItem) rateOfPay =
Convert.ToDecimal(rateListBox.SelectedItem)
CalcGrossPay(hoursWkd, rateOfPay, grossPay)
Look into Memory of variables
The variables used in exchange information between the calcButton's click event procedure and the CalcGrossPay procedures are allocated as follows:
In the calling procedure: hoursWkd 41.0 40000 rateOfPay 8.0 40016
In the called procedure: hoursWkd 41.0 60000 rateOfPay 8.0 60016
Passing Variables by Reference (Cont'd)
Example
Private Sub CalcGrossPay(ByVal hours As Decimal, _ ByVal rate As Decimal, _ ByRef gross As Decimal)
' calculates gross pay
If hours <= 40D Then
gross = hours * rate Else
gross = hours * rate + (hours - 40D) * rate / 2D
Additional ByVal or ByRef Example
•
Tutorial 6-4 demonstrates the difference between
parameters passed ByVal & ByRef
– Passed ByVal
– Calling procedure does not “see” changes made to the value of an argument
– Passed ByRef
– Calling procedure “sees” changes made to the
Function Procedures
Similar to a Sub procedure, a function procedure is a block of code that performs a specific task.
Different from a Sub procedure, a function procedure returns a value upon completion of the task.
The concepts of passing by value and passing by
Declaring a Function
• New keyword Function
• Also new is As DataType which states the data type of
the value to be returned
• Return value is specified in a Return expression
[AccessSpecifier] Function FunctionName ([ParameterList]) _ As DataType
Function Call Example
sngTotal = Sum(sngValue1, sngValue2)
Function Sum(ByVal sngNum1 As Single, _
ByVal sngNum2 As Single) As Single Dim sngResult As Single
sngResult = sngNum1 + sngNum2 Return sngResult
End Function
• sngValue1 & sngValue2 must be data type Single – Data types must agree with parameter list
Returning Nonnumeric Values
Function IsValid(intNum As Integer) As Boolean Dim blnStatus As Boolean
If intNum >= 0 And intNum <= 100 Then blnStatus = True
Else
blnStatus = False End If
Return blnStatus End Function
Function FullName(ByVal strFirst As String, _
ByVal strLast As String) As String Dim strName As String
strName = strLast & ", " & strFirst Return strName
Visual Basic 2010 addition
•
Nullable types were added to Visual Basic
2008. In Visual Basic 2010 you can use them
as parameters. Here are two examples:
•
' Assign Nothing as the default value for
nullable optional parameter.
• Sub Calculate (ByVal x As Integer, ByVal y As Integer, Optional ByVal z As Integer? = Nothing)
• ...
• End Sub
• ' Assign an integer value to a nullable optional paramter of type Double.
• Sub Process(ByVal x As Integer, ByVal y As Integer, Optional ByVal z As Double? = 10)
• ...
Debugging Involving Procedures
• Step Into - continue to debug by single-stepping
through a procedure
• Step Over - run procedure without single-stepping,
continue single-step after the call
• Step Out - end single-stepping in procedure, continue
single-step after the call