• No results found

vbchapter6.ppt

N/A
N/A
Protected

Academic year: 2020

Share "vbchapter6.ppt"

Copied!
29
0
0

Loading.... (view fulltext now)

Full text

(1)

Topics

Procedures

• Passing arguments to Procedures

FunctionsDebugging:

Step into, over, and out of procedures and

(2)

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

(3)

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

(4)

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.

(5)

Sub Procedures vs. Function Procedures

A Sub procedure does not return a value after

performing its assigned task.

(6)

Sub Procedures

Two types of Sub procedures:

1. Event procedures

- Associated with a specific object and event

2. General Purpose Sub procedures

(7)

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

(8)

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]

(9)

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

(10)

Placing Sub Procedure in File

General Purpose Sub procedures can be placed anywhere in the Form's code module.

(11)

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

(12)

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

(13)

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

(14)

Passing Multiple Arguments

Multiple arguments separated by commasValue of first argument is copied to firstSecond 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

(15)

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;

(16)

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

(17)

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."

(18)

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")

(19)

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.

(20)

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)

(21)

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

(22)

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

(23)

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

(24)

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

(25)

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

(26)

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 SingleData types must agree with parameter list

(27)

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

(28)

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)

• ...

(29)

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

References

Related documents

Coming back to the message passing algorithm, for each data point, when message passing converges, the beliefs at each variable node give a distribution over all the hidden

Aim is to train the basic stick handling techniques like passing , receiving a pass, protecting the ball, and basic shooting skills.. With keepers basic saves from

The procedure gives primary responsibility to the insurer for notification (although in some cases it rests with the Appointed Actuary). However the procedure then

Great urge to pass stool, but nothing passed, or passing stools and feeling that there is more to come, especially if person is sedentary, elderly, or studying hard, chronic use

number, title, telephone number, post code, personal code, extended timeout on access points, anti pass-back, super pass right visitor receiving right, activate specific schedules,

Chapter 2, “ACCESS Procedure Reference,” on page 11 describes the generic options and procedure statements that enable you to create access descriptors, view descriptors, and SAS

Variable Scope (Local vs. Global)  Pass‐By‐Copy Versus Pass‐by‐Reference  Defining and Invoking Functions  Creating Function Libraries   

Introduction and Motivation Concepts Practical Information Basic Types Variables Lists For Loop Concept: Variable Variables. A variable is a reference to