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

Module 3: Language and Syntax Enhancements

The document summarizes key differences between Visual Basic 6.0 and Visual Basic .NET related to language syntax and features. It covers differences in data types, variables, functions, exception handling, and more. The document provides details on these topics to help developers understand changes to the language.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Module 3: Language and Syntax Enhancements

The document summarizes key differences between Visual Basic 6.0 and Visual Basic .NET related to language syntax and features. It covers differences in data types, variables, functions, exception handling, and more. The document provides details on these topics to help developers understand changes to the language.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 35

Module 3: Language and

Syntax Enhancements
Overview

 Data Types
 Using Variables
 Functions, Subroutines, and Properties
 Exception Handling
 Data Types

 Common Type System


 Comparing Value-Type and Reference-Type Variables
 New Data Types
 Changes to Existing Data Types
 Using CType to Convert Data Types
Common Type System

 Integrated in the common language runtime


 Shared by the runtime, compilers, and tools
 Controls how the runtime declares, uses, and manages
types
 Includes a set of predefined data types
 Common type system objects are based on the
System.Object class
Comparing Value-Type and Reference-Type Variables

 Value-Type Variables
 Directly contain their data
 Each has its own copy of data
 Operations on one cannot affect another
 Assignment creates a copy of the data
 Reference-Type Variables
 Store references to their data (known as objects)
 Two reference variables can reference the same object
 Operations on one can affect another
New Data Types

Visual Basic .NET Storage size Value range


data type

Char 2 bytes 0 to 65535 (unsigned)

Short 2 bytes -32,768 to 32,767

Decimal 12 bytes Up to 28 digits on


either side of decimal
(signed)
Changes to Existing Data Types

Visual Basic 6.0 Visual Basic .NET

Integer Short
Long (32 bits, signed) Integer
(none) Long (64 bits, signed)
Variant Not supported: use Object
Currency Not supported: use Decimal
Date No longer stored as a Double

String (fixed length) Not supported


Using CType to Convert Data Types

 Use CType to convert values from one data type to another


data type
 Similar to CStr and CInt in Visual Basic 6.0
 Syntax:
 CType (expression, typename)
 Using Variables

 Declaring and Initializing Variables and Arrays


 Declaring Multiple Variables
 Variable Scope
 Creating Data Structures
 Compiler Options
 Assignment Operators
Declaring and Initializing Variables and Arrays

 You can initialize variables when you declare them


 You can initialize arrays with a size, but they are no longer
fixed
 You can dimension arrays before using ReDim
Dim
Dim ii As
As Integer
Integer == 21
21
Dim
Dim dToday
dToday AsAs Date
Date == Today(
Today( ))

'Array
'Array declarations
declarations
Dim
Dim Month(12)
Month(12) AsAs Integer
Integer 'Creates
'Creates array
array with
with 13
13 elements
elements
'Initialize
'Initialize the
the array
array with
with 1212 elements
elements
Dim
Dim aMonth(
aMonth( )) As
As Integer
Integer == {1,2,3,4,5,6,7,8,9,10,11,12}
{1,2,3,4,5,6,7,8,9,10,11,12}
Declaring Multiple Variables

 Declaring multiple variables in Visual Basic 6.0

Dim
Dim I,
I, J,
J, XX As
As Integer
Integer
'Results
'Results inin II and
and JJ As
As Variant,
Variant, XX As
As Integer
Integer

 Declaring multiple variables in Visual Basic .NET


Dim
Dim I,
I, J,
J, XX As
As Integer
Integer
'Results
'Results inin I,I, J,
J, and
and XX As
As Integer
Integer
Variable Scope

 Procedure scope
 Variables accessible to entire procedure
 Block scope
 Variables only accessible within that block
 Lifetime of block variable is entire procedure
Dim
Dim iLooper
iLooper As
As Integer
Integer 'Procedure
'Procedure level
level variable
variable

For
For iLooper
iLooper == 11 to
to 10
10
Dim
Dim iMax
iMax As
As Integer
Integer 'Block
'Block level
level variable
variable
iMax
iMax == iLooper
iLooper
Next
Next
MsgBox
MsgBox (iMax)
(iMax) 'This
'This line
line generates
generates aa compiler
compiler error
error
Creating Data Structures

 Structures replace user-defined types


 Structures support many features of classes
 Use Structure…End Structure to declare structures
 Declare structure members with an access modifier

Structure
Structure Customer
Customer
Public
Public CustID
CustID As
As Integer
Integer
Dim
Dim CustDayPhone
CustDayPhone AsAs String
String 'Defaults
'Defaults to
to public
public
Private
Private CustNightPhone As
CustNightPhone As String
String 'Private allowed
'Private allowed
End
End Structure
Structure
Compiler Options

 Option Explicit
 Default option
 Option Strict
 Enforces strict type semantics and restricts implicit type
conversion
 Late binding by means of the Object data type is not
allowed
 Option Base 1 Not Supported
 Arrays must start at zero
Assignment Operators

 Simplified variable assignment operators

*= Multiplication
/= Division
+= Addition
-= Subtraction
&= String concatenation

 Example: iResult += 25
 iResult equals the existing value for iResult, plus 25
Demonstration: Using Variables and Data Structures
 Functions, Subroutines, and Properties

 Calling Functions and Subroutines


 Passing Arguments ByRef and ByVal
 Optional Arguments
 Static Function and Static Sub
 Returning Values from Functions
 Using Default Properties
Calling Functions and Subroutines

 Visual Basic 6.0


 You must follow complex rules regarding use of
parentheses
 You must use parentheses when using a return value
from a function
 Visual Basic .NET
 You must use parentheses to enclose the parameters of
any function or subroutine
 You must include empty parentheses for procedures
without parameters
Passing Arguments ByRef and ByVal

 Visual Basic 6.0


 ByRef is the default passing mechanism
 Visual Basic .NET
 ByVal is the default passing mechanism
Optional Arguments

 Visual Basic 6.0


 You do not need to specify default values for optional
parameters
 You can use the IsMissing function
 Visual Basic .NET
 You must include default values for optional parameters
 The IsMissing function is not supported
Function
Function Add(Value1
Add(Value1 AsAs Integer,
Integer, Value2
Value2 As
As Integer,
Integer,
Optional
Optional Value3
Value3 As
As Integer
Integer == 0)
0) As
As Integer
Integer
Static Function and Static Sub

 Visual Basic 6.0


 You can place Static in front of any Function or Sub
procedure heading
 Local variables in a static function or static subroutine
retain their values between multiple calls
 Visual Basic .NET
 Static functions and static subroutines are not supported
 You must explicitly declare all static variables
Returning Values from Functions

 Visual Basic 6.0


 Use the function name to return the value
 Visual Basic .NET
 You can use the function name
 You can also use the Return statement
Using Default Properties

 Visual Basic 6.0


 Supports default properties on most objects
 Use Set to determine whether assignment is referring to
the object or the default property
 Visual Basic .NET
 Supports default properties only for parameterized
properties
 Do not need to differentiate between object and default
property assignments
 Default properties are commonly used to index into
collections
Using Default Properties (continued)

 You can call default properties only if the property takes


parameters

Dim
Dim rs
rs As
As ADODB.Recordset,
ADODB.Recordset, Lab1
Lab1 As
As Label
Label
'…initialization
'…initialization

rs.Fields.Item(1).Value
rs.Fields.Item(1).Value == Lab1.Text
Lab1.Text 'Valid
'Valid
rs.Fields(1).Value
rs.Fields(1).Value == Lab1.Text
Lab1.Text 'Valid
'Valid

rs.Fields(1)
rs.Fields(1) == Lab1.Text
Lab1.Text 'Not
'Not valid
valid
Lab1
Lab1 == "Data
"Data Saved"
Saved" 'Not
'Not valid
valid
Lab 3.1: Working with Variables and Procedures
 Exception Handling

 Structured Exception Handling


 Try…Catch…Finally
 Using Try…Catch…Finally
 The System.Exception Class
 Filtering Exceptions
 Throwing Exceptions
Structured Exception Handling

 Disadvantages of unstructured error handling


 Code is difficult to read, debug, and maintain
 Easy to overlook errors
 Advantages of structured exception handling
 Supported by multiple languages
 Allows you to create protected blocks of code
 Allows filtering of exceptions similar to Select Case
statement
 Allows nested handling
 Code is easier to read, debug, and maintain
Try…Catch…Finally

...
...
Try
Try
'' Include
Include code
code to
to be
be tried
tried here
here
'' Can
Can use
use Exit
Exit Try
Try to
to exit
exit block
block and
and resume
resume after
after End
End Try
Try

Catch
Catch
'' Define
Define exception
exception type
type and
and action
action to
to be
be taken
taken
'' Can
Can use
use series
series of
of statements
statements (multiple
(multiple error
error handling)
handling)

Finally
Finally
'' Optional
Optional block
block
'' Define
Define actions
actions that
that need
need to
to take
take place
place

End
End Try
Try
...
...
Using Try…Catch…Finally

Sub
Sub TrySimpleException
TrySimpleException
Dim
Dim i1,
i1, i2,
i2, iResult
iResult AsAs Decimal
Decimal
i1
i1 == 22
22
i2
i2 == 00
Try
Try
iResult
iResult == i1
i1 // i2
i2 '' Cause
Cause divide-by-zero
divide-by-zero error
error
MsgBox
MsgBox (iResult)
(iResult) '' Will
Will not
not execute
execute

Catch
Catch eException
eException As
As Exception
Exception '' Catch
Catch the
the exception
exception
MsgBox
MsgBox (eException.Message)
(eException.Message) '' Show
Show message
message to
to user
user

Finally
Finally
Beep
Beep
End
End Try
Try
End
End Sub
Sub
The System.Exception Class

 Provides information about the exception


Property or method Information provided
Message property Why the exception was thrown
Source property The name of the application or object that
generated the exception
StackTrace property Exception history
InnerException property For nested exceptions
HelpLink property The appropriate Help file, URN, or URL
ToString method The name of the exception, the exception
message, the name of the inner exception,
and the stack
Filtering Exceptions
Dim
Dim x,
x, y,
y, zz As
As Integer,
Integer, bSucceeded
bSucceeded AsAs Boolean
Boolean == True
True
Try
Try
'Perform
'Perform various
various operations
operations on
on variables
variables
...
...
Catch
Catch eException
eException As As DivideByZeroException
DivideByZeroException
MsgBox("You
MsgBox("You have have attempted
attempted to
to divide
divide by
by zero.")
zero.")
bSucceeded = False
bSucceeded = False
Catch
Catch eException
eException As As OverflowException
OverflowException
MsgBox("You
MsgBox("You have encountered
have encountered an
an overflow.")
overflow.")
bSucceeded = False
bSucceeded = False
...
...
Catch
Catch When
When Err.Number
Err.Number == 11 11
MsgBox("Error
MsgBox("Error occurred.")
occurred.")
bSucceeded
bSucceeded == False
False
Finally
Finally
If
If bSucceeded
bSucceeded ThenThen
...
...
End If
End If
End Try
End Try
Throwing Exceptions

 Use Throw keyword instead of Err.Raise

Try
Try
If
If xx == 00 Then
Then
Throw
Throw NewNew Exception("x
Exception("x equals
equals zero")
zero")
Else
Else
Throw
Throw NewNew Exception("x
Exception("x does
does not
not equal
equal zero")
zero")
End
End If
If
Catch
Catch eException
eException As As Exception
Exception
MsgBox("Error:
MsgBox("Error: "" && eException.Message)
eException.Message)
Finally
Finally
MsgBox("Executing
MsgBox("Executing finally
finally block")
block")
End
End Try
Try
Demonstration: Structured Exception Handling
Lab 3.2: Implementing Structured Exception Handling
Review

 Data Types
 Using Variables
 Functions, Subroutines, and Properties
 Exception Handling

You might also like