0% found this document useful (0 votes)
22 views

3 - Procedures, Functions and Structures

This document discusses procedures, functions, structures and classes in Visual Basic.NET. It defines procedures as blocks of code that can be reused, making code easier to understand. Sub procedures perform actions without returning a value, while function procedures can return a value. Arguments can be passed by value or reference. The document provides examples of math functions and random number generation. It also discusses shared and non-shared methods, as well as date/time functions in Visual Basic.NET.

Uploaded by

shared tec
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

3 - Procedures, Functions and Structures

This document discusses procedures, functions, structures and classes in Visual Basic.NET. It defines procedures as blocks of code that can be reused, making code easier to understand. Sub procedures perform actions without returning a value, while function procedures can return a value. Arguments can be passed by value or reference. The document provides examples of math functions and random number generation. It also discusses shared and non-shared methods, as well as date/time functions in Visual Basic.NET.

Uploaded by

shared tec
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

VISUAL PROGRAMMING

WITH VISUAL BASIC.NET

VB PPT: 03 Procedures, Function, Structures and


Class

Ishara Wimaladasa (BSc,Pg dip in IT, NDTVE)


PROCEDURES
 Procedure
 A block of statements enclosed by a declaration
statement and an End statement
 Invoked from some other place in the code
 When finished the execution, returns control to the code
that invoked it
 Provide a way to break larger complex programs
into smaller and simple logical units – Divide and
conquer
 Make code easier to read, understand and debug
 Enable code reusability
 Can be a sub procedure, function procedure or an
event procedure 2
EXAMPLE
Boss

Worker 1 worker 2 Worker 3

Worker 4 Worker 5

 Boss assigns work to the workers


 A worker may assign part of his work to a subordinate
 Once the given job is completed, boss can continue
with his work
 How the worker does the work is not important here
3
SUB PROCEDURE

 Sub procedure
 A series of statements enclosed by the Sub and End Sub
statement

 Perform actions but does not return a value to the


calling code

 Can take arguments that are passed by the calling code

 Can define in modules, classes and structures

4
DECLARATION OF SUB PROCEDURES
 Declaration syntax
[AccessSpecifier] Sub Identifier ([Parameter])
[Statements]
End Sub
 Accessspecifier Could Be Public, Protected,
Friend, Or Private
 If omitted, it is public by default
 Identifier specifies the identifier of the procedure
 ParameterList is a comma-separated list of
parameters
 Exit sub statement can be used to exit
immediately form a sub procedure
5
DECLARATION OF SUB PROCEDURES
 Declaration syntax for parameters
[ByVal/ByRef] Identifier As DataType
or
optional [ByVal/ByRef] Identifier As DataType = _ DefaultValue

 ByVal or ByRef specifies the argument passing mechanism


 If omitted, it is assumed ByVal by default

 Optional indicates whether the argument is optional


 If so a default value must be declared for use in case, if the calling code
does not supply an argument

 Parameters following a parameter corresponding to an optional argument


must also be optional
6
ARGUMENT PASSING MECHANISMS
 Argument can be passed to a procedure by value or by
reference by specifying ByVal or ByRef keywords,
respectively

 Passing by value means the procedure can not modify the


contents of arguments in calling code

 Passing by reference allows the procedure to modify the


contents of arguments in calling code

 Non-variable arguments in calling code are never


modified, even if they are passed by reference
7
ARGUMENT PASSING MECHANISMS
 Passing arguments ByVal
 Protects arguments form being changed by the
procedure
 Affects to the performance due to the copying of
corresponding parameters
 Passing arguments ByRef
 Enables the procedure to return values to the calling
code through the arguments
 Reduces the overhead of copying the arguments to their
corresponding parameters but can lead to an accidental
corruption of caller’s data

8
FUNCTION PROCEDURES
 Function procedure
 A series of statements enclosed by the function and End
Function statement

 Similar to a sub procedure, but can return a value to the


calling program

 Can take arguments that are passed by the calling code

 Can define in modules, classes and structures

9
DECLARATION OF FUNCTION
PROCEDURES
 Declaration syntax
[AccessSpecifier] Function _
Identifier ( [ParameterList] ) [As DataType]
[Statement]
Return ReturnExpression
End Sub
 AccessSpecifier could be public, protected, friend or
private
 If omitted, it is public by default
 Identifier specifies the identifier of the function
 ParameterList is comma-separated list of parameters
 Data type is the data type of ReturnExpression
10
METHODS OF MATH CLASS
 Function procedure (Methods) contained in class
“Math”
 Performs mathematical operations and returns a value

Method Description Example


Abs(X) Returns the absolute value of Abs (-23.5) is 23.5
X
Ceiling(X) Round X to the smaller Ceiling(9.2) is 10.0
integer not less than X
Cos(X) Returns trigonometric cosine Cos(0.0) is 1.0
of X
Exp(1.0) is
Exp(X) Returns the exponential eX 2.728281828459
05 approximately
11
METHODS OF MATH CLASS
Method Description Example
Floor(X) Rounds X to the largest integer not Floor(9.2) is 9.0
greater than X
Log(X) Returns the natural logarithm of X Log(2.7182818284
(base e) 5905)
Is 1.0 app.
Max(X,Y) Returns the maximum value of X & Y Max (5.8) is 8
Min(X)pow(X,Y) Returns the minimum value of X & Y Min (5.8) is 5
Pow(X,Y) Calculates X raised to power Y Pow (2.0,7.0) is 128
Sin(X) Returns the trigonometric sine of X Sin(0.0) is 0.0
Sqrt(X) Returns the square root of X Sqrt (9.0) is 3.0
Tan(X) Returns the trigonometric tangent of Tan (0.0) is 0.0
X
Round(X) Rounds X, If given the # of decimal Round (2.3) is 2
Round(X,dp) places, it rounds to that decimal
places
12
RANDOM NUMBER GENERATION
 What is a random number?
Dim RandomObject as new Random()
Dim RandNum as Integer = RandoObject .Next ()

 This generates a positive integer from 0 to Int32.MaxValue


i.e. 2,147,483,647
 We can give the range to procedure random numbers
Value = rando object .Next (1.7)

 This returns a value between 1-6


 If passed only one parameter, it will return a value from 0
to the passed value but excluding that value
 Rnd () returns a random number between 0 and 1
13
SHARE METHODS AND NON
SHARED METHODS
 Shared Methods Are Defined In The Base Class
And Could Be Used Without Mentioning The
Instance Name
 Ex:
Imports System .String
Compare (Strl . Str2) compare is a method in the string class
 Non Shared Methods Should be used with the
instance to which they belong
 Ex:
Di Strl As string
If Strl .EndsWith (“ed”) Then …. 14
METHODS OF STRING CLASS
Method Description
EndsWith(X) Checks whether the string instance ends with x
Equals(X) Checks whether the string instance equals x
Indexof(X) Returns the index where string x is found in the given string
Insert(strtindex, X) X will be inserted into the given string starting at the given position
Remove(strIndex,NofChrs) Removes the given # of characters starting at the given position
Replace(oldstr, newstr) Replace the old string part with the new one
Startswith(X) Checks whether the string instance starts with x
ToLower(), toUpper() Converts to Lower Case or Upper Case
Trim(), TrimEnd(), Remove spaces from both sides, from start or from end
TrimStart()

15
FUNCTION TO DETERMINE DATA
TYPE

Method Description
IsArray(Variable Name) Checks whether the Variable is an array
IsData(Expression) Checks whether the expression is a valid data or time value
IsNumeric(Expression) Checks whether the expression evaluates to a numeric value
IsObject(Variable Name) Checks whether the variable is an object
Is Nothing Checks whether the object is set to nothing
If objMyObject Is Nothing then ….
TypeOf Checks the type of an object variable
If TypeOf txtName is TextBox Then …
TypeName(Variable Name) Returns the data type of a non object type variable

16
DATE / TIME FUNCTIONS
 When a Date type variable is declared, CLR uses
the Date Time structure, which has an extensible
list of properties and methods
Now () and Today (0 are two shared members
 Ex.
datToday = Today()
 Non shared members could be used with the
instance name of the Date Time structure

17
DATE / TIME FUNCTIONS

Method Description
Date Date Component
Day Integer day of month (1-31)
DayOfWeek Integer day of week (0 = Sunday)
DayOfyear Integer day of year (1-366)
Hour Integer hour (0-23)
Minute Integer minute (0-59)
Second Integer second (0-59)
Month Integer month (1 = January)
Year Year component
ToLongDateString Date formatted as long date
ToLongtimeString Date formatted as long time
ToShortdateString Date formatted as short date
ToShortTimeString Date formatted as short time

18
IN BUILT STRING FUNCTIONS
Function description Example
InStr Finds the starting position of a substring within InStr(“My mother”, “mo”) = 4
a string
LCase Converts a string lower case LCase(“UPPER Case”) = upper case
Left Finds or removes a specified number of Left(“Kelaniye”, 6) = “Kelani”
Characters from the beginning of a string
Len Gives the length of a string Len(“Hello”) = 5
LTrim Removes spaces from the beginning of a string LTrim(“Hello”) = “Hello”
Mid Finds or removes characters from a Mid(“Microsoft”,3,4) = :cros”
String
StrRevers Reverses the string strReverse(“Kelaniya”) = “ayinaleK”
Right Finds or removes a specified number of Right(“Kelaniya”, 6) = “laniya”
Characters from the end of a string
RTrim Removes spaces from the end of a string RTime(“ Hello “) = “Hello”
Str Removes the string equivalent of a number Str(12345) = “12345”
Trim Trims spaces from both the beginning and end Trim(“ Hello “) = “Hello”
of a string
UCase Converts a string to upper case UCase(“lower Case”) = “UPPER CASE”

19
RECURSIVE PROCEDURES
 A procedure calls itself for a repetitive task
 Ex. Calculating the Factorial Value
private Function Factorial (ByVal X As Int32) As Long
If X = 1 Then
Return 1
Else
Return X * Factorial (X - 1)
End function

 Any problem that can be solved recursively could


be solved iteratively
 But recursions more naturally mirrors some
problems, hence easy to understand and debug
20
CLASSES
 Standard programming unit in OOP

 Encapsulate data members and member


functions into one package

 Enable inheritance and polymorphism

 Act as a template for creating objects

21
DECLARATION OF CLASSES
 Declaration syntax
[AccessSpecifier] Class identifier
[Inherits Baseclass]
[MemberVariableDeclarations]
[MemberFunctionDeclarations]
End class

 AccessSpecifier could be public, protected, Friend, or


private
 If omitted, it is Friend by default
 Baseclass specifies class that gives the inheritance
 Members could be Dim, public, protected, friend, or
private
22
OBJECT VARIABLES
 Variables can also be used to refer objects
 Data type should be either of Object or the particular
class type
 Syntax
 New keyword
 Instructs to create an instance of the specified class type &
to assign a reference to the variable

 Class the constructor of specified class type

 If omitted, creates an empty variable capable of holding a


reference to an object of the specified class type
23
ASSIGNMENT OPERATOR WITH
OBJECTS
 Assign a reference to an object to a variable
 If variable is empty, New operator to create an
object of the specified class type and to assign a
reference to that object
 Syntax
Variable = New ClassType
 Assigning Nothing to a variable breaks its
reference to any object
 Syntax
Variable = Nothing

24
OBJECTS VARIABLES
 Members of an object can be accessed with the period character
 Syntax
objectVariable.Member
 To set a value to a property
objectVariable. property = Expression
 To get the value in a property
objectVariable.property
 To call a method
objectVariable.Method [ArgumentList]
 To handle an event

sub objectVariable_ Event (EventArgs) Handles


objectVariable. Event
[statements]
end sub 25
PROGRAMMING WITH OBJECTS
VARIABLES
 In many situations, several actions are required
to perform on a same object
 With statement can be used to refer multiple
members of an object without specifying the
object variable multiple times in code
 Syntax
with objectVariable
[. Property]
[. Method ([Arguments])]
End With
 Makes code run faster & helps to avoid repetitive typing

26
RESOURCE MANAGEMENT WITH OBJECTS
 Objects consume system resource such as
memory, file handles & database connections
 CLR manages resource automatically and
usually no need to worry about releasing them
of unwanted objects
 However, managing resources consumed by
objects makes programs more efficient
 Assign nothing to any unwanted object to release its
resources immediately
 Syntax
objectVariable.Dispose (True)
27
MODULES
 Like classes, encapsulate data members and
member functions defined within
 Unlike classes, modules can never be
instantiated and do not support inheritance
 Public members declared in a module are
accessible from anywhere in the project without
using their fully qualified names or an Imports
statement
 Known as global members
 Global variables and constants declared in a
module exist throughout the life of the program

28
DECLARATION OF MODULES
 Declaration syntax
[AccessSpecifier] Module Identifier
[MemberVariableDeclarations]
[MemberFunctionDeclarations]
End Module

 AccessSpecifier could only be public or friend


 If omitted, it is friend by default
 Members could be Dim, public, protected, friend,
or private

29
SCOPE
 Scope of a declared element is the region in which it is
available and can be referred without using its fully
qualified name or an imports statement
 Element could be a variable, constant, procedure, class,
structure or an enumeration
 Use care when declaring elements with the same
identifier but with a different scope, because doing so can
lead to unexpected results
 If possible, narrowing the scope of elements when
declaring them is a good programming practice 30
BLOCK LEVEL SCOPE
 A block is a set of statements terminated by an
End, Else, Loop, or Next statement

 An element declared within a block is accessible


only within that block

 Element could be a variable or a constant

 Even through scope of a block element is limited


to the block, it will exists throughout the
procedure that the block declared
31
PROCEDURE LEVEL SCOPE
 Also referred to as method level scope
 An element declared within a procedure is
accessible and available only within that
procedure
 Element could be a variable or a constant
 Known as local elements
 All local variables should only be declared using
Dim as the access specifier and private by
default

32
MODULE LEVEL SCOPE
 Applies equally to modules, classes, and structures scope of
an element declared within a module is determined by the
access specifier used at the declaration

 Elements at this level should be declared outside of any


procedure or block in the module

 Element could be a variable, constant, procedure, class,


structure or an enumeration

 Except for structures, variables declared using Dim as the


access specifier are private by default 33
ACCESSIBILITY OF ELEMENTS
 Accessibility of element declared at module level
 Public elements
Accessible from anywhere within the same project and from
other projects that reference the project
 Friend elements
Accessible from within the same project, but not from outside
the project
 Protected elements
Accessible only from within the same class, or from a class
derived from that class
 Private elements
Accessible only from within the same module, class, or
structure
34
END OF THE LECTURE

 Any
REFERENCE
 https://youtu.be/g9B1K1gJws8
 https://youtu.be/w-Poc242WoE

 https://youtu.be/w-Poc242WoE

You might also like