Download presentation
Presentation is loading. Please wait.
1
Subs, Functions and Events
1
2
Outline Introduction VB.NET Procedures Sub Procedures Function Procedures Methods Argument Promotion Value Types and Reference Types Passing Arguments: Pass-by-Value vs. Pass-by-Reference Duration of Identifiers Scope Rules Events
3
VB.NET Procedures Framework Class Library
Provides a rich collection of “prepackaged” classes and methods for performing many operations Mathematical calculations String manipulations Character manipulations Input/output operations
4
VB.NET Procedures Programmer-defined procedures
FCL cannot provide every conceivable feature that a programmer could want Three types of procedures Sub procedures Function procedures Event procedures A procedure is invoked by a procedure call
5
Payment.vb Program Output
Console application uses a Sub procedure (invoked from the application’s Main procedure) to print a worker’s payment information. 1 ' Fig. 6.2: Payment.vb 2 ' Sub procedure that prints payment information. 3 4 Module modPayment 5 Sub Main() 7 ' call Sub procedure PrintPay 4 times PrintPay(40, 10.5) PrintPay(38, 21.75) PrintPay(20, 13) PrintPay(50, 14) 13 Console.ReadLine() ' prevent window from closing End Sub ' Main 16 ' print amount of money earned in command window Sub PrintPay(ByVal hours As Double, ByVal wage As Decimal) 19 ' pay = hours * wage Console.WriteLine("The payment is {0:C}", hours * wage) End Sub ' PrintPay 23 24 End Module ' modPayment Payment.vb Program Output PrintPay receives the values of each argument and stores them in the parameters variables hours and wage The payment is $420.00 The payment is $826.50 The payment is $260.00 The payment is $700.00 Notice that PrintPay appears within modPayment. All procedures must be defined inside a module or a class
6
Sub Procedures The program contains two procedure definitions:
Sub procedure Main, which executes when the console application is loaded. Sub procedure PrintPay, which executes when it is invoked, or called, from another procedure, in this case Main.
7
Sub Procedures Format of a procedure definition
Sub procedure-name(parameter-list) declarations and statements End Sub Procedure header: ByVal: specifies that the calling program should pass a copy of the value of the argument in the procedure call to the parameter, which can be used in the Sub procedure body. Procedure-name Directly follows the Sub keyword Can be any valid identifier Procedure body The declarations and statements in the procedure definition form the procedure body
8
Common Errors Declaring a variable in the procedure’s body with the same name as a parameter variable in the procedure header is a syntax error. Although it is allowable, an argument passed to a procedure should not have the same name as the corresponding parameter in the procedure definition. This distinction prevents ambiguity that could lead to logic errors. Defining a procedure inside another procedure is a syntax error—procedures cannot be nested. The procedure header and procedure calls all must agree with regard to the number, type and order of parameters.
9
Function Procedures Similar to Sub procedures
One important difference: Function procedures return a value to the caller, whereas Sub procedures do not.
10
Console application uses Function procedure Square to calculate the squares of the Integers from 1–10. 1 ' Fig. 6.3: SquareInteger.vb 2 ' Function procedure to square a number. 3 4 Module modSquareInteger 5 Sub Main() Dim i As Integer ' counter 8 Console.WriteLine("Number" & vbTab & "Square" & vbCrLf) 10 ' square numbers from 1 to 10 For i = 1 To 10 Console.WriteLine(i & vbTab & Square(i)) Next 15 End Sub ' Main 17 ' Function Square is executed ' only when the function is explicitly called. Function Square(ByVal y As Integer) As Integer Return y ^ 2 End Function ' Square 23 24 End Module ' modSquareInteger The For structure displays the results of squaring the Integers from 1-10 Square is invoked with the expression Square(i) The Return statement terminates execution of the procedure and returns the result of y ^ 2
11
Program Output Number Square 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81
12
Function Procedures Format of a Function procedure definition
Function procedure-name(parameter-list) As return-type declarations and statements End Function Return-type: Indicates the data type of the result returned from the Function to its caller Return expression Can occur anywhere in a Function It returns exactly one value Control returns immediately to the point at which that procedure was invoked
13
Common Errors If the expression in a Return statement cannot be converted to the Function procedure’s return-type, a runtime error is generated. Failure to return a value from a Function procedure (e.g., by forgetting to provide a Return statement) causes the procedure to return the default value for the return-type, often producing incorrect output.
14
EX1- Maximum Number 1 ' Fig. 6.4: Maximum.vb 2 ' Program finds the maximum of three numbers input. 3 4 Public Class FrmMaximum 5 ' obtain values in each text box, call procedure Maximum Private Sub btnMaximum_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMaximum.Click Dim value1, value2, value3 As Double 9 value1 = txtFirst.Text value2 = txtSecond.Text value3 = txtThird.Text 13 lblMaximum.Text = Maximum(value1, value2, value3) End Sub ' cmdMaximum_Click 16 ' find maximum of three parameter values Function Maximum(ByVal valueOne As Double, ByVal valueTwo As Double, ByVal valueThree As Double) As Double 19 Return Math.Max(Math.Max(valueOne, valueTwo), valueThree) End Function ' Maximum 22 23 End Class ' FrmMaximum Event handler btnMaximum_Click Handles the event in which Button btnMaximum is clicked
16
EX2- Sorting Array Bubble Sort (a.k.a. sinking sort)
Smaller values “bubble” their way to the top of the array, (i.e. toward the first element) Larger values “sink” to the bottom of the array, (i.e. toward the end) The bubble sort is easy to program, but runs slowly Becomes apparent when sorting large arrays
17
Sub BubbleSort Sub Swap Sub cmdCreate_Click Sub cmdSort_Click
1 Public Class FrmBubbleSort Dim array As Integer() = New Integer(9) { } ' sort array using bubble sort algorithm Sub BubbleSort(ByVal sortArray As Integer()) Dim pass, i As Integer 6 For pass = 1 To sortArray.GetUpperBound(0) 8 For i = 0 To sortArray.GetUpperBound(0) - 1 10 If sortArray(i) > sortArray(i + 1) Then Swap(sortArray, i) End If Next Next 16 End Sub ' BubbleSort 17 Sub Swap(ByVal swapArray As Integer(), ByVal first As Integer) Dim hold As Integer hold = swapArray(first) swapArray(first) = swapArray(first + 1) swapArray(first + 1) = hold End Sub ' Swap Sub BubbleSort Sub Swap Sub cmdCreate_Click Sub cmdSort_Click
18
25 ' creates random generated numbers
24 ' creates random generated numbers Private Sub cmdCreate_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdCreate.Click 28 Dim output As String Dim randomNumber As Random = New Random() Dim i As Integer txtSorted.Text = "“ ' create 10 random numbers and append to output For i = 0 To array.GetUpperBound(0) array(i) = randomNumber.Next(100) output &= array(i) & vbCrLf Next 38 txtOriginal.Text = output ' display numbers cmdSort.Enabled = True ' enables cmdSort button End Sub ' cmdCreate_Click txtOriginal.Text txtSorted.Text cmdCreate cmdSort
19
42 ' randomly generated numbers
Private Sub cmdSort_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdSort.Click 45 Dim output As String Dim i As Integer 48 ' sort array BubbleSort(array) 51 ' creates string with sorted numbers For i = 0 To array.GetUpperBound(0) output &= array(i) & vbCrLf Next 56 txtSorted.Text = output ' display numbers cmdSort.Enabled = False End Sub ' cmdSort_Click 60 61 End Class ' FrmBubbleSort
21
EX3- Searching Arrays: Linear Search
The process of locating a particular element value in an array Linear Search Simple searching technique Works well for small or unsorted arrays
22
Compares each element of the array with a search key
Function LinearSearch Sub cmdCreate_Click Sub cmdSearch_Click 1 Public Class FrmLinearSearchTest 2 Dim array1 As Integer() = New Integer(19) {} ' iterates through array 5 6 Function LinearSearch(ByVal key As Integer, ByVal numbers As Integer()) As Integer 7 Dim n As Integer 9 ' structure iterates linearly through array For n = 0 To numbers.GetUpperBound(0) 12 If numbers(n) = key Then 14 Return n End If 17 Next 19 Return -1 End Function ' LinearSearch Compares each element of the array with a search key If the search key is not found, the procedure returns –1, a non-valid index number
23
txtInput txtData lblResult cmdSearch cmdCreate
' creates random data Private Sub cmdCreate_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdCreate.Click 25 Dim output As String Dim randomNumber As Random = New Random() Dim i As Integer 29 output = "Index" & vbTab & "Value" & vbCrLf ' creates string containing 11 random numbers For i = 0 To array1.GetUpperBound(0) array1(i) = randomNumber.Next(1000) output &= i & vbTab & array1(i) & vbCrLf Next 36 txtData.Text = output ' displays numbers txtInput.Text = "" ' clear search key text box cmdSearch.Enabled = True ' enable search button End Sub ' cmdCreate_Click txtData lblResult cmdSearch cmdCreate txtInput
24
41 ' searches key of element
Private Sub cmdSearch_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdSearch.Click 44 ' if search key text box is empty, display ' message and exit procedure If txtInput.Text = "" Then MessageBox.Show("You must enter a search key.") Exit Sub End If 51 Dim searchKey As Integer = Convert.ToInt32(txtInput.Text) Dim element As Integer = LinearSearch(searchKey, array1) 54 If element <> -1 Then lblResult.Text = "Found Value in index " & element Else lblResult.Text = "Value Not Found" End If 60 End Sub ' cmdSearch_Click 62 63 End Class ' FrmLinearSearch
26
Argument Promotion Coercion of arguments
The forcing of arguments to be appropriate data type so that they can be passed to a procedure. Visual Basic supports both: Widening conversion Occurs when a type is converted to another type without losing data Narrowing conversion Occurs when there is potential for data loss during the conversion
27
Argument Promotion Fig. 6.8 Widening conversions.
28
Value Types and Reference Types
All Visual Basic data types can be categorized as either: Variable of a value type Contains the actual data Used for a single piece of data the integral types (Byte, Short, Integer and Long), the floating-point types (Single and Double) and types Boolean, Date, Decimal and Char. Variable of a reference type Contains a location in memory where data is stored. Known as objects Arrays String.
29
Passing Arguments: Pass-by-Value vs. Pass-by-Reference
The program makes a copy of the argument’s value and passes that copy to the called procedure changes to the called procedure’s copy do not affect the original variable’s value. Pass-by-reference The caller gives the called procedure the ability to access and modify the caller’s original data directly.
30
When number1 is passed, a copy of the value is passed to the procedure
1 ' Fig. 6.12: ByRefTest.vb 2 ' Demonstrates passing by reference. 3 4 Module modByRefTest 5 ' squares three values ByVal and ByRef, displays results Sub Main() Dim number1 As Integer = 2 9 Console.WriteLine("Passing a value-type argument by value:") Console.WriteLine("Before calling SquareByValue, " & _ "number1 is {0}", number1) SquareByValue(number1) ' passes number1 by value Console.WriteLine("After returning from SquareByValue, " & _ "number1 is {0}" & vbCrLf, number1) 16 Dim number2 As Integer = 2 18 Console.WriteLine("Passing a value-type argument" & _ " by reference:") Console.WriteLine("Before calling SquareByReference, " & _ "number2 is {0}", number2) SquareByReference(number2) ' passes number2 by reference Console.WriteLine("After returning from " & _ "SquareByReference, number2 is {0}" & vbCrLf, number2) 26 Dim number3 As Integer = 2 28 When number1 is passed, a copy of the value is passed to the procedure A reference to the value stored in number2 is being passed
31
ByVal indicates that value-type arguments should be passed by value
Console.WriteLine("Passing a value-type argument" & _ " by reference, but in parentheses:") Console.WriteLine("Before calling SquareByReference " & _ "using parentheses, number3 is {0}", number3) SquareByReference((number3)) ' passes number3 by value Console.WriteLine("After returning from " & _ "SquareByReference, number3 is {0}", number3) 36 End Sub ' Main 38 ' squares number by value (note ByVal keyword) Sub SquareByValue(ByVal number As Integer) Console.WriteLine("After entering SquareByValue, " & _ "number is {0}", number) number *= number Console.WriteLine("Before exiting SquareByValue, " & _ "number is {0}", number) End Sub ' SquareByValue 47 ' squares number by reference (note ByRef keyword) Sub SquareByReference(ByRef number As Integer) Console.WriteLine("After entering SquareByReference" & _ ", number is {0}", number) number *= number Console.WriteLine("Before exiting SquareByReference" & _ ", number is {0}", number) End Sub ' SquareByReference 56 57 End Module ' modByRefTest Enclosing arguments in parenthesis forces pass-by-value even if using ByRef ByVal indicates that value-type arguments should be passed by value ByRef gives direct access to the value stored in the original variable
32
Program Output Passing a value-type argument by value:
Before calling SquareByValue, number1 is 2 After entering SquareByValue, number is 2 Before exiting SquareByValue, number is 4 After returning from SquareByValue, number1 is 2 Passing a value-type argument by reference: Before calling SquareByReference, number2 is 2 After entering SquareByReference, number is 2 Before exiting SquareByReference, number is 4 After returning from SquareByReference, number2 is 4 Passing a value-type argument by reference, but in parentheses: Before calling SquareByReference using parentheses, number3 is 2 After returning from SquareByReference, number3 is 2
33
Passing Arguments: Pass-by-Value vs. Pass-by-Reference
Passing value-type arguments with keyword ByRef is useful when procedures need to alter argument values directly. However, passing by reference can weaken security, because the called procedure can modify the caller’s data. Reference-type variables passed with keyword ByVal are effectively passed by reference, as the value that is copied is the reference for the object. Although Visual Basic allows programmers to use keyword ByRef with reference-type parameters, it is usually not necessary to do so except with type String.
34
Duration of Identifiers
Identifier’s duration: Period during which the identifier exists in memory Automatic duration Identifiers that represent local variables in a procedure have automatic duration Instance variable A variable declared in a class They exist as long as their containing class is loaded in memory Identifier’s scope: Portion of a program in which the variable’s identifier can be referenced
35
Scope Rules Possible scopes Class scope Module scope Namespace scope
Begins at the class identifier after keyword Class and terminates at the End Class statement Module scope Variable declared in a module have module scope, which is similar to class scope Namespace scope Procedures defined in a module have namespace scope, which generally means that they may be accessed throughout a project Block scope Identifiers declared inside a block, such as the body of a procedure definition or the body of an If/Then selection structure, have block scope
36
1 ' Fig. 6.13: Scoping.vb 2 ' Demonstrates scope rules and instance variables. 3 4 Public Class FrmScoping Inherits System.Windows.Forms.Form 6 Friend WithEvents lblOutput As System.Windows.Forms.Label 8 ' Windows Form Designer generated code 10 ' instance variable can be used anywhere in class Dim value As Integer = 1 13 ' demonstrates class scope and block scope Private Sub FrmScoping_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load 17 ' variable local to FrmScoping_Load hides instance variable Dim value As Integer = 5 20 lblOutput.Text = "local variable value in" & _ " FrmScoping_Load is " & value 23 MethodA() ' MethodA has automatic local value MethodB() ' MethodB uses instance variable value MethodA() ' MethodA creates new automatic local value MethodB() ' instance variable value retains its value 28 lblOutput.Text &= vbCrLf & vbCrLf & "local variable " & _ "value in CScoping_Load is " & value End Sub ' FrmScoping_Load This variable is hidden in any procedure that declares a variable named value
37
32 ' automatic local variable value hides instance variable
Sub MethodA() Dim value As Integer = 25 ' initialized after each call 36 lblOutput.Text &= vbCrLf & vbCrLf & "local variable " & _ "value in MethodA is " & value & " after entering MethodA" value += 1 lblOutput.Text &= vbCrLf & "local variable " & _ "value in MethodA is " & value & " before exiting MethodA" End Sub ' MethodA 43 ' uses instance variable value Sub MethodB() lblOutput.Text &= vbCrLf & vbCrLf & "instance variable" & _ " value is " & value & " after entering MethodB" value *= 10 lblOutput.Text &= vbCrLf & "instance variable " & _ "value is " & value & " before exiting MethodB" End Sub ' MethodB 52 53 End Class ' FrmScoping Automatic variable value is destroyed when MethodA terminates When MethodB procedure refers to variable value, the instance variable value (line 12) is used.
39
Events An event is something that happens. Your birthday is an event.
An event in programming terminology is when something special happens. These events are so special that they are built in to the programming language. VB.NET has numerous Events that you can write code for. And we’re going to explore some of them in this course. We’ll start with all that mysterious code for the Button’s Click Event.
40
The Click Event Buttons have the ability to be clicked on.
When you click a button, the event that is fired is the Click Event. If you were to add a new button to a form, and then double clicked it, you would see the following code stub: Private Sub btnOutput_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles btnOutput.Click End Sub
41
The Click Event Private Sub btnOutput_Click(ByVal sender As Object, _
For example suppose we want the Button btnOutput to respond when clicked by showing a message box with the statement Button was clicked. Private Sub btnOutput_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles btnOutput.Click MessageBox.Show(“Button was clicked.") End Sub An event is a message sent by an object announcing that something has happened. When events occurs, information is passed to Event handlers ( Here it is btnOutput.Click).
42
The Click Event This is a Private Subroutine.
The name of the Sub is btnOutput_Click. The Event itself is at the end: btnOutput.Click. The Handles word means that this Subroutine can Handle the Click Event of btnOutput. You can have this btnOutput_Click Sub Handle other things, too. It can Handle the Click Event of other Buttons, for example. Handles btnOutput.Click, Button2.Click
44
Event Handler Arguments
Event handlers take two arguments: An Object (usually sender) : Instead of sender being an integer or string variable, the type of variable set up for sender is System.Object. This stores a reference to a control (which button was clicked, for example). 2. An event arguments object (e) : An instance of type EventArgs. Class EventArgs is the base class for objects that contain event information.
45
Other Events Fig Events section of the Properties window.
46
Conclusion Experience has shown that the best way to develop and maintain a large program is to construct it from small, manageable pieces. This technique is known as divide and conquer. Visual Basic programs consist of many pieces, including modules and classes. Three types of procedures exist: Sub procedures, Function procedures and event procedures.
47
Conclusion The characteristics of Function procedures are similar to those of Sub procedures. However, Function procedures return a value to the caller. If a Function procedure body does not specify a Return statement, program control returns to the point at which a procedure was invoked when the End Function keywords are encountered.
48
Conclusion An event represents a user action, such as the clicking of a button. Widening conversion occurs when a type is converted to another type without losing data. Narrowing conversion occurs when there is potential for data loss during a conversion. Some narrowing conversions can fail, resulting in runtime errors and logic errors.
49
Conclusion Option Explicit, which is set to On by default, forces the programmer to declare all variables explicitly before they are used in a program. Forcing explicit declarations eliminates spelling errors and other subtle errors that may occur if Option Explicit is turned Off. Option Strict, which is set to Off by default, increases program clarity and reduces debugging time. When set to On, Option Strict requires the programmer to perform all narrowing conversions explicitly.
50
Conclusion All data types can be categorized as either value types or reference types. A variable of a value type contains data of that type. A variable of a reference type contains the location in memory where the data is stored.
51
Conclusion Arguments are passed in one of two ways: Pass-by-value and pass-by-reference. When an argument is passed by value, the program makes a copy of the argument’s value and passes that copy to the called procedure. Changes to the called procedure’s copy do not affect the original variable’s value. When an argument is passed by reference, the caller gives the procedure the ability to access and modify the caller’s original data directly. Pass-by-reference can improve performance, because it eliminates the need to copy large data items, such as large objects; however, pass-by-reference can weaken security, because the called procedure can modify the caller’s data.
52
Conclusion Value-type arguments enclosed in parentheses, (), are passed by value even if the procedure header declares the parameter with keyword ByRef. An identifier’s duration (also called its lifetime) is the period during which the identifier exists in memory. Identifiers that represent local variables in a procedure (i.e., parameters and variables declared in the procedure body) have automatic duration. Automatic-duration variables are created when program control enters the procedure in which they are declared, exist while the procedure is active and are destroyed when the procedure is exited.
53
Conclusion The scope of a variable, reference or procedure identifier is the portion of the program in which the identifier can be accessed. The possible scopes for an identifier are class scope, module scope, namespace scope and block scope.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.