SlideShare une entreprise Scribd logo
1  sur  32
Télécharger pour lire hors ligne
Visual Programming with
Visual Basic .NET
Procedures, Functions and Structures
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
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
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
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
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 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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

Contenu connexe

Tendances

C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams Ahmed Farag
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingIqra khalil
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual BasicSangeetha Sg
 
Operators in java presentation
Operators in java presentationOperators in java presentation
Operators in java presentationkunal kishore
 
Lecture 1 introduction to vb.net
Lecture 1   introduction to vb.netLecture 1   introduction to vb.net
Lecture 1 introduction to vb.netMUKALU STEVEN
 
Exception Handling in VB.Net
Exception Handling in VB.NetException Handling in VB.Net
Exception Handling in VB.Netrishisingh190
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++Nilesh Dalvi
 
TCP/IP Protocols With All Layer Description
TCP/IP Protocols With All Layer DescriptionTCP/IP Protocols With All Layer Description
TCP/IP Protocols With All Layer DescriptionShubham Khedekar
 
arrays and pointers
arrays and pointersarrays and pointers
arrays and pointersSamiksha Pun
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++Shyam Gupta
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVAAnkita Totala
 

Tendances (20)

Vb 6.0 controls
Vb 6.0 controlsVb 6.0 controls
Vb 6.0 controls
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
class and objects
class and objectsclass and objects
class and objects
 
Java Beans
Java BeansJava Beans
Java Beans
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual Basic
 
Operators in java presentation
Operators in java presentationOperators in java presentation
Operators in java presentation
 
Lecture 1 introduction to vb.net
Lecture 1   introduction to vb.netLecture 1   introduction to vb.net
Lecture 1 introduction to vb.net
 
Exception Handling in VB.Net
Exception Handling in VB.NetException Handling in VB.Net
Exception Handling in VB.Net
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
TCP/IP Protocols With All Layer Description
TCP/IP Protocols With All Layer DescriptionTCP/IP Protocols With All Layer Description
TCP/IP Protocols With All Layer Description
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
arrays and pointers
arrays and pointersarrays and pointers
arrays and pointers
 
Applets
AppletsApplets
Applets
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
Ip address
Ip addressIp address
Ip address
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Visual Basic Controls ppt
Visual Basic Controls pptVisual Basic Controls ppt
Visual Basic Controls ppt
 

En vedette

Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)pbarasia
 
Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0Salim M
 
Visual basic ppt for tutorials computer
Visual basic ppt for tutorials computerVisual basic ppt for tutorials computer
Visual basic ppt for tutorials computersimran153
 
Introduction to visual basic programming
Introduction to visual basic programmingIntroduction to visual basic programming
Introduction to visual basic programmingRoger Argarin
 
Introduction to VB
Introduction to VBIntroduction to VB
Introduction to VBMukesh Das
 
Pass by value and pass by reference
Pass by value and pass by reference Pass by value and pass by reference
Pass by value and pass by reference TurnToTech
 
Part 12 built in function vb.net
Part 12 built in function vb.netPart 12 built in function vb.net
Part 12 built in function vb.netGirija Muscut
 
Menu pop up menu mdi form and playing audio in vb
Menu pop up menu mdi form and playing audio in vbMenu pop up menu mdi form and playing audio in vb
Menu pop up menu mdi form and playing audio in vbAmandeep Kaur
 
Vb net xp_04
Vb net xp_04Vb net xp_04
Vb net xp_04Niit Care
 
Vb net xp_11
Vb net xp_11Vb net xp_11
Vb net xp_11Niit Care
 
Date & time functions in VB.NET
Date & time functions in VB.NETDate & time functions in VB.NET
Date & time functions in VB.NETA R
 
Mdi Presentation
Mdi PresentationMdi Presentation
Mdi PresentationKieran Lamb
 
Procedure text
Procedure textProcedure text
Procedure textinantia
 

En vedette (20)

Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)
 
Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0
 
Visual basic ppt for tutorials computer
Visual basic ppt for tutorials computerVisual basic ppt for tutorials computer
Visual basic ppt for tutorials computer
 
INPUT BOX- VBA
INPUT BOX- VBAINPUT BOX- VBA
INPUT BOX- VBA
 
Introduction to visual basic programming
Introduction to visual basic programmingIntroduction to visual basic programming
Introduction to visual basic programming
 
Introduction to VB
Introduction to VBIntroduction to VB
Introduction to VB
 
Pass by value and pass by reference
Pass by value and pass by reference Pass by value and pass by reference
Pass by value and pass by reference
 
Notas InputBox
Notas InputBoxNotas InputBox
Notas InputBox
 
InputBox
InputBoxInputBox
InputBox
 
Part 12 built in function vb.net
Part 12 built in function vb.netPart 12 built in function vb.net
Part 12 built in function vb.net
 
Date function
Date functionDate function
Date function
 
Menu pop up menu mdi form and playing audio in vb
Menu pop up menu mdi form and playing audio in vbMenu pop up menu mdi form and playing audio in vb
Menu pop up menu mdi form and playing audio in vb
 
Vb net xp_04
Vb net xp_04Vb net xp_04
Vb net xp_04
 
Vb
VbVb
Vb
 
Active x
Active xActive x
Active x
 
Vb net xp_11
Vb net xp_11Vb net xp_11
Vb net xp_11
 
Date & time functions in VB.NET
Date & time functions in VB.NETDate & time functions in VB.NET
Date & time functions in VB.NET
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 
Mdi Presentation
Mdi PresentationMdi Presentation
Mdi Presentation
 
Procedure text
Procedure textProcedure text
Procedure text
 

Similaire à Procedures functions structures in VB.Net

Variable and constants in Vb.NET
Variable and constants in Vb.NETVariable and constants in Vb.NET
Variable and constants in Vb.NETJaya Kumari
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Abou Bakr Ashraf
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Palak Sanghani
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...vekariyakashyap
 
Breaking down data silos with the open data protocol
Breaking down data silos with the open data protocolBreaking down data silos with the open data protocol
Breaking down data silos with the open data protocolWoodruff Solutions LLC
 
procedures and arrays
procedures and arraysprocedures and arrays
procedures and arraysDivyaR219113
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And RefactoringNaresh Jain
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
Advanced c#
Advanced c#Advanced c#
Advanced c#saranuru
 
PPT ON VHDL subprogram,package,alias,use,generate and concurrent statments an...
PPT ON VHDL subprogram,package,alias,use,generate and concurrent statments an...PPT ON VHDL subprogram,package,alias,use,generate and concurrent statments an...
PPT ON VHDL subprogram,package,alias,use,generate and concurrent statments an...Khushboo Jain
 
Chapter2pp
Chapter2ppChapter2pp
Chapter2ppJ. C.
 

Similaire à Procedures functions structures in VB.Net (20)

Variable and constants in Vb.NET
Variable and constants in Vb.NETVariable and constants in Vb.NET
Variable and constants in Vb.NET
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Java q ref 2018
Java q ref 2018Java q ref 2018
Java q ref 2018
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
 
CIS160 final review
CIS160 final reviewCIS160 final review
CIS160 final review
 
Breaking down data silos with the open data protocol
Breaking down data silos with the open data protocolBreaking down data silos with the open data protocol
Breaking down data silos with the open data protocol
 
procedures and arrays
procedures and arraysprocedures and arrays
procedures and arrays
 
VB.net
VB.netVB.net
VB.net
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
VHDL lecture 2.ppt
VHDL lecture 2.pptVHDL lecture 2.ppt
VHDL lecture 2.ppt
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
vb.net.pdf
vb.net.pdfvb.net.pdf
vb.net.pdf
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Of Lambdas and LINQ
Of Lambdas and LINQOf Lambdas and LINQ
Of Lambdas and LINQ
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
PPT ON VHDL subprogram,package,alias,use,generate and concurrent statments an...
PPT ON VHDL subprogram,package,alias,use,generate and concurrent statments an...PPT ON VHDL subprogram,package,alias,use,generate and concurrent statments an...
PPT ON VHDL subprogram,package,alias,use,generate and concurrent statments an...
 
Chapter2pp
Chapter2ppChapter2pp
Chapter2pp
 

Plus de tjunicornfx

C++ Question & Answer
C++ Question & AnswerC++ Question & Answer
C++ Question & Answertjunicornfx
 
Mechanical element of a CNC Machine
Mechanical element of a CNC MachineMechanical element of a CNC Machine
Mechanical element of a CNC Machinetjunicornfx
 
AC in Vehicle -Sinhala note (Sri lanka) 1
AC in Vehicle -Sinhala note (Sri lanka) 1AC in Vehicle -Sinhala note (Sri lanka) 1
AC in Vehicle -Sinhala note (Sri lanka) 1tjunicornfx
 
AC in Vehicle -Sinhala note (Sri lanka) -3
AC in Vehicle -Sinhala note (Sri lanka) -3AC in Vehicle -Sinhala note (Sri lanka) -3
AC in Vehicle -Sinhala note (Sri lanka) -3tjunicornfx
 
AC in Vehicle -Sinhala note (Sri lanka) -2
AC in Vehicle -Sinhala note (Sri lanka) -2AC in Vehicle -Sinhala note (Sri lanka) -2
AC in Vehicle -Sinhala note (Sri lanka) -2tjunicornfx
 
Computer architecture for HNDIT
Computer architecture for HNDITComputer architecture for HNDIT
Computer architecture for HNDITtjunicornfx
 
Artificail Intelligent lec-1
Artificail Intelligent lec-1Artificail Intelligent lec-1
Artificail Intelligent lec-1tjunicornfx
 
Security architecture
Security architectureSecurity architecture
Security architecturetjunicornfx
 
04 introduction to computer networking
04 introduction to computer networking04 introduction to computer networking
04 introduction to computer networkingtjunicornfx
 

Plus de tjunicornfx (10)

C++ Question & Answer
C++ Question & AnswerC++ Question & Answer
C++ Question & Answer
 
ASP
ASPASP
ASP
 
Mechanical element of a CNC Machine
Mechanical element of a CNC MachineMechanical element of a CNC Machine
Mechanical element of a CNC Machine
 
AC in Vehicle -Sinhala note (Sri lanka) 1
AC in Vehicle -Sinhala note (Sri lanka) 1AC in Vehicle -Sinhala note (Sri lanka) 1
AC in Vehicle -Sinhala note (Sri lanka) 1
 
AC in Vehicle -Sinhala note (Sri lanka) -3
AC in Vehicle -Sinhala note (Sri lanka) -3AC in Vehicle -Sinhala note (Sri lanka) -3
AC in Vehicle -Sinhala note (Sri lanka) -3
 
AC in Vehicle -Sinhala note (Sri lanka) -2
AC in Vehicle -Sinhala note (Sri lanka) -2AC in Vehicle -Sinhala note (Sri lanka) -2
AC in Vehicle -Sinhala note (Sri lanka) -2
 
Computer architecture for HNDIT
Computer architecture for HNDITComputer architecture for HNDIT
Computer architecture for HNDIT
 
Artificail Intelligent lec-1
Artificail Intelligent lec-1Artificail Intelligent lec-1
Artificail Intelligent lec-1
 
Security architecture
Security architectureSecurity architecture
Security architecture
 
04 introduction to computer networking
04 introduction to computer networking04 introduction to computer networking
04 introduction to computer networking
 

Dernier

Education and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxEducation and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxraviapr7
 
M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxDr. Santhosh Kumar. N
 
The Singapore Teaching Practice document
The Singapore Teaching Practice documentThe Singapore Teaching Practice document
The Singapore Teaching Practice documentXsasf Sfdfasd
 
How to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesHow to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesCeline George
 
Prescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxPrescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxraviapr7
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...Nguyen Thanh Tu Collection
 
Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.raviapr7
 
Presentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphPresentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphNetziValdelomar1
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptxSandy Millin
 
Benefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationBenefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationMJDuyan
 
3.21.24 The Origins of Black Power.pptx
3.21.24  The Origins of Black Power.pptx3.21.24  The Origins of Black Power.pptx
3.21.24 The Origins of Black Power.pptxmary850239
 
How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17Celine George
 
5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...CaraSkikne1
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxKatherine Villaluna
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesMohammad Hassany
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfMohonDas
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxKatherine Villaluna
 
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfTechSoup
 
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfP4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfYu Kanazawa / Osaka University
 

Dernier (20)

Education and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxEducation and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptx
 
M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptx
 
The Singapore Teaching Practice document
The Singapore Teaching Practice documentThe Singapore Teaching Practice document
The Singapore Teaching Practice document
 
How to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesHow to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 Sales
 
Prescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxPrescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptx
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
 
Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.
 
Presentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphPresentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a Paragraph
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
 
Benefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationBenefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive Education
 
3.21.24 The Origins of Black Power.pptx
3.21.24  The Origins of Black Power.pptx3.21.24  The Origins of Black Power.pptx
3.21.24 The Origins of Black Power.pptx
 
How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17
 
Prelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quizPrelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quiz
 
5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptx
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming Classes
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdf
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
 
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
 
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfP4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
 

Procedures functions structures in VB.Net

  • 1. Visual Programming with Visual Basic .NET Procedures, Functions and Structures
  • 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