This document discusses procedures, functions, and structures in Visual Basic .NET. It defines procedures as blocks of code that can be invoked from other parts of a program and optionally accept arguments. Functions are similar but return a value. Structures allow user-defined data types. The document provides examples and explains how to declare, define parameters for, and call procedures and functions. It also covers argument passing mechanisms, built-in math and string functions, and variable scope.
2. 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
3. Example
Boss
Worker1
Worker4
Worker2
Worker5
Worker3
Click Here for
more details
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
4. Sub Procedures
Sub procedure
A series of statements enclosed by the Sub and
End Sub statements
Performs 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
5. Declaration of Sub Procedures
Declaration syntax
[AccessSpecifier] Sub Identifier([ParameterList])
[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
from a Sub procedure
5
6. 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
7. 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
8. Argument Passing Mechanisms
Passing arguments ByVal
Protects arguments from being changed by the
procedure
Affects to the performance due to the copying of
the entire data content of arguments to their
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
9. Function Procedures
Function procedure
A series of statements enclosed by the Function
and End Function statements
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
10. Declaration of Function Procedures
Declaration syntax
[AccessSpecifier] Function _
Identifier([ParameterList]) [As DataType]
[Statements]
Return ReturnExpression
End Function
AccessSpecifier could be Public, Protected, Friend,
or Private
If omitted, it is Public by default
Identifier specifies the identifier of the function
ParameterList is a comma-separated list of
parameters
DataType is the data type of ReturnExpression
10
11. Structures
Allows to create User Defined Data Types.
Once declared, a structure becomes a composite
data type and can declare variables of that
composite type
Like classes, can have data members and member
functions
Unlike classes
Structures are value type, not reference type
Can not inherit from another structure. So suitable
for objects which are more unlikely to extend
All members are Public by default
11
12. Declaration of Structures
Declaration syntax
[AccessSpecifier] Structure Identifier
MemberVariableDeclarations
[MemberFunctionDeclarations]
End Structure
Can only be declared at module or class level
AccessSpecifier could be Public, Protected, Friend, or
Private
If omitted, it is Friend by default
Members could be Dim, Public, Friend, or Private, but
not Protected
Must contain at least one member variable
Member variables can’t be initialized at the declaration
Array members should be declared without the size.
Have to use ReDim to resize.
12
13. Variables of Composite Data Types
Variables of composite data types can be declared
with the data types defined as the structures
Declaration syntax
Dim Identifier As CompositeDataType
Can be used at method, class and module levels
Identifier specifies the identifier of the variable
CompositeDataType stands for structure defined
Possible to declare several variables of same type
or of different types in one statement
13
14. Using Composite Variables
Members of a composite variable can be accessed
with the period character
Syntax
CompositeVariable.Member
To set a value to a member variable
CompositeVariable.MemberVariable = Expression
To get the value in member variable
CompositeVariable.MemberVariable
To call a member function
CompositeVariable.MemberFunction([ArgumentList])
14
15. Methods of Math Class
Function procedures (Methods) contained in class
“Math”
Performs mathematical operations and returns a
value
Method
Description
Example
Abs(x)
Returns the absolute value of x
Abs(-23.5) is 23.5
Ceiling(x)
Ceiling(9.2) is 10.0
Cos(x)
Rounds x to the smallest integer
not less than x
Returns trigonometric cosine of x
Exp(x)
Returns the exponential e
x
Cos(0.0) is 1.0
Exp(1.0) is
2.728281828459
05 approximately
15
16. Methods of Math Class
Method
Description
Example
Max(x,y)
Rounds x to the largest integer not
greater than x
Returns the natural logarithm of x
(base e)
Returns the maximum value of x & y
Min(x,y)
Returns the minimum value of x & y
Pow(x,y)
Calculates x raised to power y
Sin(x)
Returns the trigonometric sine of x
Pow(2.0,7.0) is
128
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 x
Tan(0.0) is 0.0
Round(x)
Round(X, dp)
Rounds x. If given the # of decimal
places, it rounds to that decimal places
Round(2.3) is 2
Floor(x)
Log(x)
Floor(9.2) is 9.0
Log(2.718281828459
05) is 1.0 app.
Max (5,8) is 8
Min(5,8) is 5
16
17. Random Number Generation
What is a random number?
Dim RandomObject as Random = new Random()
Dim RandNum as Integer = RandomObject.Next()
This generates a positive Integer from 0 to
Int32.Maxvalue i.e. 2,147,483,647
We can give the range to produce random
numbers.
Value = randomobject.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
17
18. Methods of String Class
Two types
Shared Methods –
No Need to mention the instance name
If Compare(strA,strB)
Non shared Methods -
>
0 Then
…
Needs to mention the instance name
If myString.EndsWith(“ed”) Then
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 strinx x is found in the given string
Insert(startindex, X)
X will be inserted into the given string starting at the given position
Remove(stIndx, 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(),
TrimStart()
Remove spaces from both sides, from start or from end
18
19. Functions to Determine Data Type
Method
Description
IsArray(Variable Name)
Checks whether the variable is an array
IsDate(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
19
20. Date / Time Functions
When a Date type variable is declared, CLR uses
the DateTime structure, which has an extensible
list of properties and methods
Now() and Today() are two shared members
Ex.
datToday = Today()
Non shared members could be used with the
instance name of the DateTime structure
20
21. 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
21
22. In Built String Functions
Function
InStr
LCase
Left
Len
LTrim
Mid
StrReverse
Right
RTrim
Str
Trim
UCase
Description
Finds the starting position of a substring
within a string
Converts a string to lower case
Finds or removes a specified number of
characters from the beginning of a string
Gives the length of a string
Removes spaces from the beginning of a
string
Finds or removes characters from a
string
Reverses the strings
Finds or removes a specified number of
characters from the end of a string
Removes spaces from the end of a string
Returns the string equivalent of a
number
Trims spaces from both the beginning
and end of a string
Converts a string to upper case
Example
InStr(“My mother”, “mo”) = 4
LCase(“UPPER Case”) = upper case
Left(“Kelaniya”, 6) = “Kelani”
Len(“Hello”) = 5
LTrim(“ Hello “) = “Hello “
Mid(“microsoft”,3,4) = “cros”
strReverse(“Kelaniya”) = “ayinaleK”
Right(“Kelaniya”, 6) = “laniya”
RTrim(“ Hello “) = “ Hello“
Str(12345) = “12345”
Trim(“ Hello “) = “Hello“
UCase(“lower Case”) = “UPPER CASE”
22
23. Recursive Procedures
A procedure calls itself for a repetitive task
Ex. Calculating the Factorial Value
Any problem that can be solved recursively could
be solved iteratively
But recursions more naturally mirrors some
problems, hence easy to understand and debug
23
24. 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
24
25. 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
25
26. 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
26
27. 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
27
28. 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
28
29. 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 though scope of a block element is limited to
the block, it will exists throughout the procedure
that the block declared
29
30. 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 are Private by
default
30
31. 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
31
32. Accessibility of Elements
Accessibility of elements 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
32