SlideShare a Scribd company logo
CHAPTER 3:
Variable and
function
scoping, Variable
Conversions
Variable scope
• The declaration of a variable establishes more than just the name and
data type of the variable.
• Depending on the keyword used to declare the variable and the
placement of the variable’s declaration in the program’s code, the variable
might be visible to large portions of the application’s code.
• Alternatively, a different placement might severely limit where the
variable can be referenced in the procedures within the application.
• The visibility of a variable or procedure is called its scope. A variable that
can be seen and used by any procedure in the application is said to have
public scope. Another variable, one that is usable by a single procedure, is
said to have scope that is private to that procedure.
Private variables
• Private variables are available to the module, class, or structure in which they are
declared.
• As with previous Visual Basic version, Dim and Private act in the same manner,
with the exception that the Private keyword cannot be used to declare variables
within a subprocedure or function.
• Here is an example of how you could use Private and Dim within a class:
Public Class Var1
Private Shared intJ as Integer
Shared Sub Main()
Dim intY as Integer = 100
Call DoSomething
Console.Writeline(intJ)
' returns 100
Console.Writeline(intY)
End Sub
Private Shared Sub DoSomething()
IntJ = 100
End Sub
End Class
Sub EatDinner() as Boolean
Private intX as integer = 100
End Sub
The following code is invalid.
Remember, Private is not
allowed to declare local
variables within a
subprocedure or function.
Public variables
• Public variables are available to all
procedures in all classes, modules, and
structures in your application.
• It is important to note that in most
cases, method and variable declaration
is public by default in VB .NET. The
following example demonstrates the
use of a public variable used in multiple
classes.
• Notice that both intX and intY are in the
Public scope, and are accessible to the
classes in the module.
Module ModMain
' This is our public variable
Public intX, intY As Integer
Public Class Dog
Sub X()
intX = 100
End Sub
Sub Y()
intY = 300
End Sub
End Class
Private Class Animals
Sub Z()
intX = 500
End Sub
End Class
End Module
Static variables
• Static variables are special variable types that retain their values within the scope of the
method or class in which they are declared.
• A static variable retains its value until the value of the variable is reset, or until the application
ends.
• In this example, each time the sub is executed, the value of intS is retained until the value
reaches 105, then the value of intX is reset to 100, and this happens forever until the
application ends.
• Static variables can only be declared at the procedure level. If you attempt to declare a variable
at the class or module level, you get a compiler error.
Static intS As Integer = 100
Sub Test()
intS = intS + 1
If intS = 105 Then
intS = 100
End If
End Sub
Shared variables
• Shared members are properties, procedures, or fields
that are shared by all instances of a class.
• This makes it easy to declare a new instance of a class,
but maintain a shared, public variable throughout all
instances of the class.
• If you are expecting variables to be initialized to empty
or null when a class is instantiated, so you should use
caution when implementing shared variables
Protected variables
• Protected variables are only available to the class in
which they are declared, or classes that derive from
the same class. Module Module1
Class A
' Declare protected variable
Protected X As Integer
Private Function TestX() As Boolean
' Set value of protected variable
X = 5
End Function
End Class
Class B
Private Function TestX() As Boolean
X = 5
End Function
End Class
End Module
In the following code, the
variable X is available only to
the class in which it is declared.
The attempt to access it in the
Class B results in an error.
Friend variables
• Friend variables are accessible from any class or module within the
assembly that they are declared in.
• In the following code, a friend variable is declared at the module level, and
the variable is available to all classes within this module.
Module Module1
' Declare Friend variable
Friend X As Integer
Class A
Private Function TestX() As Boolean
' Set value of protected variable
X = 5
End Function
End Class
Class B
Private Function TestX() As Boolean
X = 5
End Function
End Class
End Module
Data Type Conversion
In Visual Basic, data can be converted in two
ways:
• implicitly, which means the conversion is
performed automatically,
• and explicitly, which means you must
perform the conversion.
Implicit Conversions
• An implicit conversion does not require any special syntax in the source code.
• Let's understand implicit conversions in code.
• The example below declares two variable, one of type double and the other integer. The
double data type is assigned a value and is converted to integer type.
• When you run the code the result displayed is an integer value, in this case the value
displayed is 132 instead of 132.31223.
Module Module1
Sub Main()
Dim d=132.31223 as Double
Dim i as Integer
i=d
WriteLine("Integer value is" & i)
End Sub
End Module
Explicit Conversions
• An explicit conversion also called as cast uses a type
conversion keyword.
• Visual Basic provides several such keywords, which coerce an
expression in parentheses to the desired data type.
• In the following example, the CInt keyword converts the value
of double back to an integer before assigning it to an integer.
Module Module1
Sub Main()
Dim intk As Integer
Dim dblq As Double
dblq=432
dblq=Math.Sqrt(dblq)
intk= CInt(dblq)
End Sub
End Module
Widening Conversions
Data type Widens to data types
Sbyte SByte, Short, Integer, Long, Decimal, Single, Double
Byte Byte, Short, UShort, Integer, UInteger, Long, ULong, Decimal,
Single, Double
Short Short, Integer, Long, Decimal, Single, Double
Ushort UShort, Integer, UInteger, Long, ULong, Decimal, Single,
Double
Integer Integer, Long, Decimal, Single, Double
Uinteger UInteger, Long, ULong, Decimal, Single, Double
Long Long, Decimal, Single, Double
Ulong ULong, Decimal, Single, Double
Decimal Decimal, Single, Double
Single Single, Double
Double Double
Char Char, String
Narrowing Conversions
The standard narrowing conversions include the following:
• The reverse directions of the widening conversions in the preceding table
(except that every type widens to itself)
• Conversions in either direction between Boolean and any numeric type
• Conversions in either direction between String and any numeric type,
Boolean, or Date
• Conversions from a data type or object type to a type derived from it.
Narrowing conversions do not always succeed at run time, and can fail or
incur data loss. An error occurs if the destination data type cannot receive
the value being converted. You use a narrowing conversion when you know
the source value can be converted to the destination data type without error
or data loss.
Conversion Keywords
Keyword Output data type Allowable data types
CLng Long data type Any numeric type (including Byte, SByte, and
enumerated types), Boolean, String, Object
CBool Boolean data type Any valid char or string or numeric expression
CByte Byte data type Any numeric type (including SByte and
enumerated types), Boolean, String, Object
CChar Char data type String, Object
CDate Date data type String, Object
CDbl Double data type Any numeric type (including Byte, SByte, and
enumerated types), Boolean, String, Object
CDec Decimal data type Any numeric type (including Byte, SByte, and
enumerated types), Boolean, String, Object
CInt Integer data type Any numeric type (including Byte, SByte, and
enumerated types), Boolean, String, Object
Keyword Output data type Allowable data types
CObj Object data type Any type
CSByte SByte Data Type Any numeric type (including Byte and enumerated
types), Boolean, String, Object
CShort Short Data Type Any numeric type (including Byte, SByte, and
enumerated types), Boolean, String, Object
CSng Single Data Type Any numeric type (including Byte, SByte, and
enumerated types), Boolean, String, Object
CStr String Data Type Any numeric type (including Byte, SByte, and
enumerated types), Boolean, Char, Char array,
Date, Object
CType Type specified
following the
comma (,)
Conversion Keywords
The CType Function
Returns the result of explicitly converting an expression to a specified data
type, object, structure, class, or interface.
CType(expression, typename)
The CType Function operates on two arguments:
• The first (expression) is the expression to be converted,
• and the second (typename) is the destination data type or object class.
Note that the first argument must be an expression, not a type.
CType includes all of the VB conversion functions.
Value Changes During Conversions
• A conversion from a value type stores a copy of the source value in the
destination of the conversion. However, this copy is not an exact image of the
source value.
• The destination data type stores values differently, and even the value being
represented might change, depending on the kind of conversion being
performed.
• Narrowing conversions change the destination copy of the source value, with
potential information loss. (fractional value is rounded when converted to an
integral type)
• Widening conversions preserve the source value but can change its
representation. (Integral type to Decimal, or Char to String).
• The original source value is not changed as a result of a conversion.
Exceptions During Conversion
Because widening conversions always succeed, they do not
throw exceptions. Narrowing conversions, when they fail,
most commonly throw the following exceptions:
• InvalidCastException — if no conversion is defined
between the two types
• OverflowException — (integral types only) if the
converted value is too large for the target type

More Related Content

PPTX
Unit 1 introduction to visual basic programming
PPTX
CHAPTER 2 (Data types,Variables) in Visual Basic Programming
PPTX
Keywords, identifiers and data type of vb.net
DOCX
UNIT-II VISUAL BASIC.NET | BCA
PPTX
Variables and calculations_chpt_4
PPS
Visual Basic Review - ICA
PPTX
Visual Basic Fundamentals
Unit 1 introduction to visual basic programming
CHAPTER 2 (Data types,Variables) in Visual Basic Programming
Keywords, identifiers and data type of vb.net
UNIT-II VISUAL BASIC.NET | BCA
Variables and calculations_chpt_4
Visual Basic Review - ICA
Visual Basic Fundamentals

Similar to Variable, Functions, Scoping and Variable Conversion (20)

PDF
vb.net.pdf
PPT
Visual basic intoduction
PPTX
Variable and constants in Vb.NET
PPTX
VB.NET Datatypes.pptx
PPT
VB.net
PPTX
Chapter 03
PDF
Learning VB.NET Programming Concepts
PPT
Ppt lesson 05
PPT
Lesson 5 PP
DOCX
VBScript datatypes and control structures.docx
PPTX
CHAPTER 3- Lesson A
PPTX
Fundamentals of .Net Programming concepts
PPT
Introduction to VB.Net By William Lacktano.ppt
PDF
Notes how to work with variables, constants and do calculations
PPTX
E learning excel vba programming lesson 3
PDF
Visual Basics for Application
PPTX
Module 3 : using value type variables
PPT
ملخص البرمجة المرئية - الوحدة الثالثة
PPTX
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
PPT
Ms vb
vb.net.pdf
Visual basic intoduction
Variable and constants in Vb.NET
VB.NET Datatypes.pptx
VB.net
Chapter 03
Learning VB.NET Programming Concepts
Ppt lesson 05
Lesson 5 PP
VBScript datatypes and control structures.docx
CHAPTER 3- Lesson A
Fundamentals of .Net Programming concepts
Introduction to VB.Net By William Lacktano.ppt
Notes how to work with variables, constants and do calculations
E learning excel vba programming lesson 3
Visual Basics for Application
Module 3 : using value type variables
ملخص البرمجة المرئية - الوحدة الثالثة
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
Ms vb
Ad

More from abacusgtuc (6)

PPTX
Introduction to Visual Basic Programming
PPT
network-security_for cybersecurity_experts
PDF
Cybersecurity_Security_architecture_2023.pdf
PDF
ch04_network-vulnerabilities-and-attacks.pdf
PPT
psychology of everyday things_and_design_concepts.ppt
PDF
Information Security Planning and Risk Analysis
Introduction to Visual Basic Programming
network-security_for cybersecurity_experts
Cybersecurity_Security_architecture_2023.pdf
ch04_network-vulnerabilities-and-attacks.pdf
psychology of everyday things_and_design_concepts.ppt
Information Security Planning and Risk Analysis
Ad

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Electronic commerce courselecture one. Pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Modernizing your data center with Dell and AMD
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
MYSQL Presentation for SQL database connectivity
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Electronic commerce courselecture one. Pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Spectral efficient network and resource selection model in 5G networks
Review of recent advances in non-invasive hemoglobin estimation
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Unlocking AI with Model Context Protocol (MCP)
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Modernizing your data center with Dell and AMD
Diabetes mellitus diagnosis method based random forest with bat algorithm
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Chapter 3 Spatial Domain Image Processing.pdf
Network Security Unit 5.pdf for BCA BBA.

Variable, Functions, Scoping and Variable Conversion

  • 2. Variable scope • The declaration of a variable establishes more than just the name and data type of the variable. • Depending on the keyword used to declare the variable and the placement of the variable’s declaration in the program’s code, the variable might be visible to large portions of the application’s code. • Alternatively, a different placement might severely limit where the variable can be referenced in the procedures within the application. • The visibility of a variable or procedure is called its scope. A variable that can be seen and used by any procedure in the application is said to have public scope. Another variable, one that is usable by a single procedure, is said to have scope that is private to that procedure.
  • 3. Private variables • Private variables are available to the module, class, or structure in which they are declared. • As with previous Visual Basic version, Dim and Private act in the same manner, with the exception that the Private keyword cannot be used to declare variables within a subprocedure or function. • Here is an example of how you could use Private and Dim within a class: Public Class Var1 Private Shared intJ as Integer Shared Sub Main() Dim intY as Integer = 100 Call DoSomething Console.Writeline(intJ) ' returns 100 Console.Writeline(intY) End Sub Private Shared Sub DoSomething() IntJ = 100 End Sub End Class Sub EatDinner() as Boolean Private intX as integer = 100 End Sub The following code is invalid. Remember, Private is not allowed to declare local variables within a subprocedure or function.
  • 4. Public variables • Public variables are available to all procedures in all classes, modules, and structures in your application. • It is important to note that in most cases, method and variable declaration is public by default in VB .NET. The following example demonstrates the use of a public variable used in multiple classes. • Notice that both intX and intY are in the Public scope, and are accessible to the classes in the module. Module ModMain ' This is our public variable Public intX, intY As Integer Public Class Dog Sub X() intX = 100 End Sub Sub Y() intY = 300 End Sub End Class Private Class Animals Sub Z() intX = 500 End Sub End Class End Module
  • 5. Static variables • Static variables are special variable types that retain their values within the scope of the method or class in which they are declared. • A static variable retains its value until the value of the variable is reset, or until the application ends. • In this example, each time the sub is executed, the value of intS is retained until the value reaches 105, then the value of intX is reset to 100, and this happens forever until the application ends. • Static variables can only be declared at the procedure level. If you attempt to declare a variable at the class or module level, you get a compiler error. Static intS As Integer = 100 Sub Test() intS = intS + 1 If intS = 105 Then intS = 100 End If End Sub
  • 6. Shared variables • Shared members are properties, procedures, or fields that are shared by all instances of a class. • This makes it easy to declare a new instance of a class, but maintain a shared, public variable throughout all instances of the class. • If you are expecting variables to be initialized to empty or null when a class is instantiated, so you should use caution when implementing shared variables
  • 7. Protected variables • Protected variables are only available to the class in which they are declared, or classes that derive from the same class. Module Module1 Class A ' Declare protected variable Protected X As Integer Private Function TestX() As Boolean ' Set value of protected variable X = 5 End Function End Class Class B Private Function TestX() As Boolean X = 5 End Function End Class End Module In the following code, the variable X is available only to the class in which it is declared. The attempt to access it in the Class B results in an error.
  • 8. Friend variables • Friend variables are accessible from any class or module within the assembly that they are declared in. • In the following code, a friend variable is declared at the module level, and the variable is available to all classes within this module. Module Module1 ' Declare Friend variable Friend X As Integer Class A Private Function TestX() As Boolean ' Set value of protected variable X = 5 End Function End Class Class B Private Function TestX() As Boolean X = 5 End Function End Class End Module
  • 9. Data Type Conversion In Visual Basic, data can be converted in two ways: • implicitly, which means the conversion is performed automatically, • and explicitly, which means you must perform the conversion.
  • 10. Implicit Conversions • An implicit conversion does not require any special syntax in the source code. • Let's understand implicit conversions in code. • The example below declares two variable, one of type double and the other integer. The double data type is assigned a value and is converted to integer type. • When you run the code the result displayed is an integer value, in this case the value displayed is 132 instead of 132.31223. Module Module1 Sub Main() Dim d=132.31223 as Double Dim i as Integer i=d WriteLine("Integer value is" & i) End Sub End Module
  • 11. Explicit Conversions • An explicit conversion also called as cast uses a type conversion keyword. • Visual Basic provides several such keywords, which coerce an expression in parentheses to the desired data type. • In the following example, the CInt keyword converts the value of double back to an integer before assigning it to an integer. Module Module1 Sub Main() Dim intk As Integer Dim dblq As Double dblq=432 dblq=Math.Sqrt(dblq) intk= CInt(dblq) End Sub End Module
  • 12. Widening Conversions Data type Widens to data types Sbyte SByte, Short, Integer, Long, Decimal, Single, Double Byte Byte, Short, UShort, Integer, UInteger, Long, ULong, Decimal, Single, Double Short Short, Integer, Long, Decimal, Single, Double Ushort UShort, Integer, UInteger, Long, ULong, Decimal, Single, Double Integer Integer, Long, Decimal, Single, Double Uinteger UInteger, Long, ULong, Decimal, Single, Double Long Long, Decimal, Single, Double Ulong ULong, Decimal, Single, Double Decimal Decimal, Single, Double Single Single, Double Double Double Char Char, String
  • 13. Narrowing Conversions The standard narrowing conversions include the following: • The reverse directions of the widening conversions in the preceding table (except that every type widens to itself) • Conversions in either direction between Boolean and any numeric type • Conversions in either direction between String and any numeric type, Boolean, or Date • Conversions from a data type or object type to a type derived from it. Narrowing conversions do not always succeed at run time, and can fail or incur data loss. An error occurs if the destination data type cannot receive the value being converted. You use a narrowing conversion when you know the source value can be converted to the destination data type without error or data loss.
  • 14. Conversion Keywords Keyword Output data type Allowable data types CLng Long data type Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object CBool Boolean data type Any valid char or string or numeric expression CByte Byte data type Any numeric type (including SByte and enumerated types), Boolean, String, Object CChar Char data type String, Object CDate Date data type String, Object CDbl Double data type Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object CDec Decimal data type Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object CInt Integer data type Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object
  • 15. Keyword Output data type Allowable data types CObj Object data type Any type CSByte SByte Data Type Any numeric type (including Byte and enumerated types), Boolean, String, Object CShort Short Data Type Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object CSng Single Data Type Any numeric type (including Byte, SByte, and enumerated types), Boolean, String, Object CStr String Data Type Any numeric type (including Byte, SByte, and enumerated types), Boolean, Char, Char array, Date, Object CType Type specified following the comma (,) Conversion Keywords
  • 16. The CType Function Returns the result of explicitly converting an expression to a specified data type, object, structure, class, or interface. CType(expression, typename) The CType Function operates on two arguments: • The first (expression) is the expression to be converted, • and the second (typename) is the destination data type or object class. Note that the first argument must be an expression, not a type. CType includes all of the VB conversion functions.
  • 17. Value Changes During Conversions • A conversion from a value type stores a copy of the source value in the destination of the conversion. However, this copy is not an exact image of the source value. • The destination data type stores values differently, and even the value being represented might change, depending on the kind of conversion being performed. • Narrowing conversions change the destination copy of the source value, with potential information loss. (fractional value is rounded when converted to an integral type) • Widening conversions preserve the source value but can change its representation. (Integral type to Decimal, or Char to String). • The original source value is not changed as a result of a conversion.
  • 18. Exceptions During Conversion Because widening conversions always succeed, they do not throw exceptions. Narrowing conversions, when they fail, most commonly throw the following exceptions: • InvalidCastException — if no conversion is defined between the two types • OverflowException — (integral types only) if the converted value is too large for the target type