SlideShare a Scribd company logo
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

More Related Content

What's hot (20)

PPTX
Event handling
swapnac12
 
PPTX
OOPS In JAVA.pptx
Sachin33417
 
PPTX
Python Libraries and Modules
RaginiJain21
 
PPTX
Dempster shafer theory
Dr. C.V. Suresh Babu
 
PPTX
structured programming
Ahmad54321
 
PPTX
Classes objects in java
Madishetty Prathibha
 
PPT
C++ classes tutorials
Mayank Jain
 
PPT
Chapter 14 - Protection
Wayne Jones Jnr
 
PPTX
Operators used in vb.net
Jaya Kumari
 
PPTX
Event Handling in java
Google
 
PPT
Function Oriented Design
Sharath g
 
PPTX
Java Data Types
Spotle.ai
 
PPSX
Control Structures in Visual Basic
Tushar Jain
 
PPTX
[OOP - Lec 18] Static Data Member
Muhammad Hammad Waseem
 
PPTX
Operator overloading
Burhan Ahmed
 
PPTX
Windowforms controls c#
prabhu rajendran
 
PPTX
Interface in java
PhD Research Scholar
 
PPT
Swing and AWT in java
Adil Mehmoood
 
PPTX
Video display devices
shalinikarunakaran1
 
PPTX
Procedural vs. object oriented programming
Haris Bin Zahid
 
Event handling
swapnac12
 
OOPS In JAVA.pptx
Sachin33417
 
Python Libraries and Modules
RaginiJain21
 
Dempster shafer theory
Dr. C.V. Suresh Babu
 
structured programming
Ahmad54321
 
Classes objects in java
Madishetty Prathibha
 
C++ classes tutorials
Mayank Jain
 
Chapter 14 - Protection
Wayne Jones Jnr
 
Operators used in vb.net
Jaya Kumari
 
Event Handling in java
Google
 
Function Oriented Design
Sharath g
 
Java Data Types
Spotle.ai
 
Control Structures in Visual Basic
Tushar Jain
 
[OOP - Lec 18] Static Data Member
Muhammad Hammad Waseem
 
Operator overloading
Burhan Ahmed
 
Windowforms controls c#
prabhu rajendran
 
Interface in java
PhD Research Scholar
 
Swing and AWT in java
Adil Mehmoood
 
Video display devices
shalinikarunakaran1
 
Procedural vs. object oriented programming
Haris Bin Zahid
 

Viewers also liked (20)

PPTX
Objects and classes in Visual Basic
Sangeetha Sg
 
PPTX
Presentation on visual basic 6 (vb6)
pbarasia
 
PPTX
Basic controls of Visual Basic 6.0
Salim M
 
PPT
Visual basic ppt for tutorials computer
simran153
 
PPT
INPUT BOX- VBA
ViVek Patel
 
PPT
Introduction to visual basic programming
Roger Argarin
 
PPTX
Introduction to VB
Mukesh Das
 
PPTX
Pass by value and pass by reference
TurnToTech
 
PPS
Notas InputBox
Ricardo Viqueira
 
PPS
InputBox
Ricardo Viqueira
 
PDF
Part 12 built in function vb.net
Girija Muscut
 
PPTX
Date function
Jignesh Patel
 
PPTX
Menu pop up menu mdi form and playing audio in vb
Amandeep Kaur
 
PPS
Vb net xp_04
Niit Care
 
PPT
Active x
andrew20827
 
PPS
Vb net xp_11
Niit Care
 
PPTX
Date & time functions in VB.NET
A R
 
PPT
User Defined Functions
Praveen M Jigajinni
 
PPT
Mdi Presentation
Kieran Lamb
 
Objects and classes in Visual Basic
Sangeetha Sg
 
Presentation on visual basic 6 (vb6)
pbarasia
 
Basic controls of Visual Basic 6.0
Salim M
 
Visual basic ppt for tutorials computer
simran153
 
INPUT BOX- VBA
ViVek Patel
 
Introduction to visual basic programming
Roger Argarin
 
Introduction to VB
Mukesh Das
 
Pass by value and pass by reference
TurnToTech
 
Notas InputBox
Ricardo Viqueira
 
Part 12 built in function vb.net
Girija Muscut
 
Date function
Jignesh Patel
 
Menu pop up menu mdi form and playing audio in vb
Amandeep Kaur
 
Vb net xp_04
Niit Care
 
Active x
andrew20827
 
Vb net xp_11
Niit Care
 
Date & time functions in VB.NET
A R
 
User Defined Functions
Praveen M Jigajinni
 
Mdi Presentation
Kieran Lamb
 
Ad

Similar to Procedures functions structures in VB.Net (20)

PDF
Unit iii vb_study_materials
gayaramesh
 
PPT
Introduction to VB.Net By William Lacktano.ppt
DonWilliam5
 
PPTX
Sharbani bhattacharya VB Structures
Sharbani Bhattacharya
 
PPS
Visual Basic Review - ICA
emtrajano
 
PPT
Visual basic 6.0
Aarti P
 
PPT
06 procedures
Jomel Penalba
 
PPTX
Keywords, identifiers and data type of vb.net
Jaya Kumari
 
PPT
Classes and objects object oriented programming
areebakanwal12
 
PPT
Lecture 5
Soran University
 
PPTX
VB.net&OOP.pptx
BharathiLakshmiAAssi
 
PPTX
VB.NET Datatypes.pptx
SubashiniRathinavel
 
PDF
procedures and arrays
DivyaR219113
 
PPT
Ch (2)(presentation) its about visual programming
nimrastorage123
 
DOCX
UNIT-II VISUAL BASIC.NET | BCA
Raj vardhan
 
PDF
10 ap week 7 vbnet statements-genesis eugenio
DaniloAggabao
 
PPTX
01 Database Management (re-uploaded)
bluejayjunior
 
PDF
Ppt on visual basics
younganand
 
PPTX
10 Functions.pptx DSDFDFDFDFDFDFDFDFFDFDFD
RuzelAmpoan1
 
Unit iii vb_study_materials
gayaramesh
 
Introduction to VB.Net By William Lacktano.ppt
DonWilliam5
 
Sharbani bhattacharya VB Structures
Sharbani Bhattacharya
 
Visual Basic Review - ICA
emtrajano
 
Visual basic 6.0
Aarti P
 
06 procedures
Jomel Penalba
 
Keywords, identifiers and data type of vb.net
Jaya Kumari
 
Classes and objects object oriented programming
areebakanwal12
 
Lecture 5
Soran University
 
VB.net&OOP.pptx
BharathiLakshmiAAssi
 
VB.NET Datatypes.pptx
SubashiniRathinavel
 
procedures and arrays
DivyaR219113
 
Ch (2)(presentation) its about visual programming
nimrastorage123
 
UNIT-II VISUAL BASIC.NET | BCA
Raj vardhan
 
10 ap week 7 vbnet statements-genesis eugenio
DaniloAggabao
 
01 Database Management (re-uploaded)
bluejayjunior
 
Ppt on visual basics
younganand
 
10 Functions.pptx DSDFDFDFDFDFDFDFDFFDFDFD
RuzelAmpoan1
 
Ad

More from tjunicornfx (10)

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

Recently uploaded (20)

PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
PDF
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PPTX
Controller Request and Response in Odoo18
Celine George
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
Controller Request and Response in Odoo18
Celine George
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Horarios de distribución de agua en julio
pegazohn1978
 

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