2. UNIT II
Page 2
2.1 DECLARATION
The Dim statement is usedfor declaring the variable using any data type. It can also be used for declaring the
variable of type enumeration, structure, class, or interface. We can specify different data types for different
variables by using a separate As clause for each variable we declare. Alternatively, we can declare several
variables to be of the same type by using a common As clause. Each variable takes the data type specifiedin the
first As clause encounteredafter its variablename part.
Dim A As Integer
Public A As Integer
2.1.1 How to declare multiple variables in a single line
Dim A, B As Integer, STR As String
Dim A As Integer : Dim B As Double
Note:
We can specify each variable's data type in the Dim statement. We can also specify an initial value. If we
do not, Visual Basic uses default settings.
We can use Dim only at module or procedure level.
Undeclared variables and variables declared without data types are assignedthe Object data type but it
can cause slow execution.
2.1.2 How to Declare Constant
We use the Const statement to declare a constant and set its value. By declaring a constant, we assign a
meaningful name to a value. Once a constant is declared, it cannot be modified or assigneda new value. If we
have a value that never changes in our application, we can define a named constant and use it in place of a literal
value. A name is easier to remember than a value. We can define the constant just once and use it in many
places in our code. If in a later version we needto redefine the value, the Const statement is the only place we
needto make a change.
Dim Const DaysInYear = 365
Private Const Days = 7
Public Const Funday As String = "Sunday"
2.1.3 How to declare multiple constants in a single line
Public Const Four As Integer = 4, Five As Integer = 5, Six As Integer = 44
2.1.4 Enumerations
Enumerations provide a convenient way to work with sets of relatedconstants and to associate constant values
with names which are easier to remember than their values. This also improves the readability of code because all
the relatedvalues use the same enumeration name. For example, we can declare an enumeration for a set of
integer constants associatedwith the days of the week, and then use the names of the days rather than their
integer values in your code. To create an enumeration we use Enum keyword followed by the enumeration name.
We can also specify the type of enumeration as Byte, Integer, Long, SByte, Short, UInteger, ULong, or UShort.
Each member takes the enumeration's data type. If we do not specify data type for the enumeration than the
default data type will be Integer.
Enum Days
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
End Enum
Console.WriteLine(Days. Sunday)
Note:
3. UNIT II
Page 3
Visual Basic initializes the first member with value zero if no value is given to it followed by an (n+1)
progression
Enumerations do not necessarily needto follow a sequential ordering. For example:-
Enum BoilingPoints As Byte
Fahrenheit = 212
Celcius = 100
End Enum
Console.WriteLine(BoilingPoints. Celcius)
If the value of a member exceeds the allowable range for the underlying data type, or if you initialize any
member to the maximum value allowed by the underlying data type, the compiler reports an error.
Values of enumeration can repeat. For example:-
Enum Colors
Red = 1
Brown = 2
Green = 1
End Enum
2.2 DECLARATION AND ASSIGNMENT
Dim A As Integer = 1
Dim A As Integer = 1, B As Double = 2
Dim A As Integer = 1 : Dim B As Double = 2
Dim STR As String = "HELLO"
Dim STR As String = "THIS IS A LONG SENTENCE" _
& "WHICH WE WANT TO PRINT"
Dim a As Integer = 1 _
& 2
2.2.1 ADVANTAGES OF LOCAL VARIABLES
1. Name Conflict Avoidance. Local variable names are not susceptible to conflict. For example, you can
create several different procedures containing a variable called intTemp. As long as each intTempis
declared as a local variable, each procedure recognizes only its own version of intTemp. Any one procedure
can alter the value in its local intTempwithout affecting intTempvariables in other procedures.
2. Memory Consumption. Local variables consume memory only while their procedure is running. Their
memory is releasedwhen the procedure returns to the calling code.
2.3 DATA TYPES
The data type of a programming element refers to what kindof data it can hold and how it stores that data.
Following are the data type in Visual Basic:-
TYPE CLR TYPE
STRUCTURE
STORAGE
ALLOCATION
VALUE RANGE
Boolean Boolean Depends on platform True or False
Byte Byte 1 byte 0 through 255 (unsigned)
Char
(single
character)
Char 2 bytes 0 through 65535 (unsigned)
Date DateTime 8 bytes 0:00:00 (midnight) on January 1, 0001 through
11:59:59 PM on December 31, 9999
Decimal Decimal 16 bytes 0 through +/-
79,228,162,514,264,337,593,543,950,335 (+/-
7.9...E+28) † with no decimal point; 0 through +/-
7.9228162514264337593543950335 with 28
places to the right of the decimal;
smallest nonzero number is +/-
4. UNIT II
Page 4
0.0000000000000000000000000001 (+/-1E-28) †
Double
(double-
precision
floating-
point)
Double 8 bytes -1.79769313486231570E+308 through -
4.94065645841246544E-324 † for negative
values;
4.94065645841246544E-324 through
1.79769313486231570E+308 † for positive values
Integer Int32 4 bytes -2,147,483,648 through 2,147,483,647 (signed)
Long (long
integer)
Int64 8 bytes -9,223,372,036,854,775,808 through
9,223,372,036,854,775,807 (9.2...E+18 †) (signed)
Object Object (class) 4 bytes on 32-bit
platform
8 bytes on 64-bit
platform
Any type can be stored in a variable of type Object
SByte SByte 1 byte -128 through 127 (signed)
Short
(short
integer)
Int16 2 bytes -32,768 through 32,767 (signed)
Single
(single-
precision
floating-
point)
Single 4 bytes -3.4028235E+38 through -1.401298E-45 † for
negative values;
1.401298E-45 through 3.4028235E+38 † for
positive values
String
(variable-
length)
String (class) Depends on
implementing platform
0 to approximately 2 billion Unicode characters
UInteger UInt32 4 bytes 0 through 4,294,967,295 (unsigned)
ULong UInt64 8 bytes 0 through 18,446,744,073,709,551,615
(1.8...E+19 †) (unsigned)
User-
Defined
(structure)
(inherits from
ValueType)
Depends on
implementing platform
Each member of the structure has a range
determinedby its data type and independent of
the ranges of the other members
UShort UInt16 2 bytes 0 through 65,535 (unsigned)
Note:
The Object Data Type is the root type in the .NET Framework and in Visual Basic which means that all
other data types and object types are derivedfrom it. It also means that any other data type can be
converted to Object.
2.3.1 Boolean Data Type
1. It holds values that can be only True or False. The keywords True and False correspond to the two states
of Boolean variables.
2. We can use the Boolean data type to contain two-state values such as true/false, yes/no, or on/off.
3. The default value of Boolean is False.
4. The corresponding type in the .NET Framework is the System.Boolean structure.
Dim A As Boolean
If A = false Then
System.Console.write("default value of boolean is false")
End If
5. UNIT II
Page 5
Note:
When Visual Basic converts numeric data type values to Boolean, 0 becomes False and all other values
become True. When Visual Basic converts Boolean values to numeric types, False becomes 0 and True
becomes -1.
2.3.2 Byte Data Type
1. Holds unsigned8-bit (1-byte) integers that range in value from 0 through 255.
2. Use the Byte data type to contain binary data.
3. The default value of Byte is 0.
Note:
Byte is an unsignedtype so it cannot represent a negative number. If we use the unary minus (-) operator
on an expression that evaluates to type Byte, Visual Basic converts the expression to Short first.
The Byte data type widens to Short, UShort, Integer, UInteger, Long, ULong, Decimal, Single, or
Double. This means we can convert Byte to any of these types without encountering a
System.OverflowException error.
The corresponding type in the .NET Framework is the System.Byte structure.
2.3.3 Char Data Type
1. Holds unsigned2-byte code points ranging in value from 0 through 65535. Each code point, or character
code, represents a single Unicode character.
2. Use the Char data type when we need to hold only a single character anddo not needthe overheadof
String. In some cases we can use Char(), an array of Char elements, to hold multiple characters.
3. The default value of Char is the character with a code point of 0.
4. Visual Basic does not convert directly between Char and the numeric types. We can use the Asc, AscW
Functions to convert a Char value to an Integer. We can use the Chr, ChrW Functions to convert an
Integer value to a Char.
5. The first 128 code points (0–127) of Unicode correspond to the letters and symbols on a standard U.S.
keyboard. These first 128 code points are the same as those the ASCII character set defines. The second
128 code points (128–255) represent special characters, such as Latin-based alphabet letters, accents,
currency symbols, and fractions. Unicode uses the remaining code points (256-65535) for a wide variety of
symbols, including worldwide textual characters, diacritics, and mathematical andtechnical symbols.
Note:
Char is an unsignedtype and cannot represent a negative value. In any case, we should not use Char to
hold numeric values.
The Char data type widens to String. This means we can convert Char to String and will not encounter a
System.OverflowException error.
Appending the literal type character C to a single-character string literal forces it to the Char data type.
The corresponding type in the .NET Framework is the System.Char structure.
You can use methods like IsDigit and IsPunctuation on a Char variable to determine its Unicode
classification.
6. UNIT II
Page 6
2.3.4 Date Data Type
1. It holds 8-byte values that represent dates ranging from January 1 of the year 0001 through December 31
of the year 9999, and times from 12:00:00 AM (midnight) through 11:59:59.9999999 PM.
2. The default value of Date is 0:00:00 (midnight) on January 1, 0001.
3. We must enclose a Date literal within number signs (# #). We must specify the date value in the format
M/d/yyyy, for example #5/31/1993#. This requirement is independent of our locale and our computer's
date and time format settings.The reason for this restriction is that the meaning of our code should never
change depending on the locale in which our application is running. Suppose we hard-code a Date literal
of #3/4/1998# and intendit to mean March 4, 1998. In a locale that uses mm/dd/yyyy, 3/4/1998
compiles as we intend. But suppose we deploy our application in many countries. In a locale that uses
dd/mm/yyyy, our hard-coded literal would compile to April 3, 1998. In a locale that uses yyyy/mm/dd,
the literal would be invalid(April 1998, 0003) and cause a compiler error.
4. The corresponding type in the .NET Framework is the System.DateTime structure.
5. If we convert a Date value to the String type, Visual Basic renders the date according to the short date
format specifiedby the run-time locale, and it renders the time according to the time format (either 12-
hour or 24-hour) specifiedby the run-time locale.
6. If we do not include a date in a date/time literal, Visual Basic sets the date part of the value to January 1,
0001. If we do not include a time in a date/time literal, Visual Basic sets the time part of the value to the
start of the day, that is, midnight (0:00:00).
7. Syntax: Dim DateAndTime As Date = #8/13/2002 12:14 PM#
2.3.5 Double Data Type
1. Holds signed8-byte double-precision floating-point. Double-precision numbers store an approximation of
a real number.
2. The Double data type provides the largest and smallest possible magnitudes for a number.
3. The default value of Double is 0.
4. The floating-point data types do not have any internal representation of trailing zero characters. For
example, they do not distinguish between 4.2000 and 4.2. Consequently, trailing zero characters do not
appear when we display or print floating-point values.
5. Appending the literal type character R to a literal forces it to the Double data type. Appending the
identifier type character # to any identifier forces it to Double.
6. The corresponding type in the .NET Framework is the System.Double structure.
2.3.6 Decimal Data Type
1. Holds signed16-byte values representing 96-bit (12-byte) integer numbers scaledby a variable power of
10. The scaling factor specifies the number of digits to the right of the decimal point; it ranges from 0
through 28.
2. It is particularly suitable for calculations, such as financial, that require a large number of digits but
cannot tolerate rounding errors.
3. The default value of Decimal is 0.
4. Decimal is not a floating-point data type. The Decimal structure holds a binary integer value, together
with a sign bit and an integer scaling factor that specifies what portion of the value is a decimal fraction.
Because of this, Decimal numbers have a more precise representation in memory than floating-point
types (Single and Double). The Decimal data type is the slowest of all the numeric types. We should
weigh the importance of precision against performance before choosing a data type.
5. The Decimal data type widens to Single or Double. This means we can convert Decimal to either of these
types without encountering a System.OverflowException error.
7. UNIT II
Page 7
6. Visual Basic does not store trailing zeros in a Decimal literal. However, a Decimal variable preserves any
trailing zeros acquired computationally. The following example illustrates this.
7. Appending the literal type character D to a literal forces it to the Decimal data type. Appending the
identifier type character @ to any identifier forces it to Decimal.
8. The corresponding type in the .NET Framework is the System.Decimal structure.
2.3.7 Integer Data Type
1. Holds signed32-bit (4-byte) integers that range in value from -2,147,483,648 through 2,147,483,647.
2. The Integer data type provides optimal performance on a 32-bit processor. The other integral types are
slower to load and store from and to memory.
3. The default value of Integer is 0.
4. The Integer data type widens to Long, Decimal, Single, or Double. This means we can convert Integer to
any one of these types without encountering a System.OverflowException error.
5. Appending the literal type character I to a literal forces it to the Integer data type. Appending the
identifier type character % to any identifier forces it to Integer.
6. The corresponding type in the .NET Framework is the System.Int32 structure.
2.3.8 Long Data Type
1. Holds signed64-bit (8-byte) integers ranging in value from -9,223,372,036,854,775,808 through
9,223,372,036,854,775,807 (9.2...E+18)
2. Use the Long data type to contain integer numbers that are too large to fit in the Integer data type.
3. The default value of Long is 0.
4. The Long data type widens to Decimal, Single, or Double. This means we can convert Long to any one of
these types without encountering a System.OverflowException error.
5. Appending the literal type character L to a literal forces it to the Long data type. Appending the identifier
type character & to any identifier forces it to Long.
6. The corresponding type in the .NET Framework is the System.Int64 structure.
2.3.9 Object Data Type
1. Holds 32-bit (4-byte) addresses that refer to objects. We can assign any reference type (string, array, class,
or interface) to an Object variable. An Object variable can also refer to data of any value type (numeric,
Boolean, Char, Date, structure, or enumeration).
2. The Object data type can point to data of any data type. We can use Object data type when we do not
know at compile time what data type the variable might point to. Whatever data type it refers to, an
Object variable does not contain the data value itself, but rather a pointer to the value. It always uses four
bytes in computer memory, but this does not include the storage for the data representing the value of the
variable. Because of the code that uses the pointer to locate the data, Object variables holding value types
are slightly slower to access than explicitly typed variables. Performance. A variable you declare with the
Object type is flexible enough to contain a reference to any object. However, when you invoke a method or
property on such a variable, you always incur late binding (at run time). To force early binding (at compile
time) and better performance, declare the variable with a specific class name, or cast it to the specific data
type.
3. The default value of Object is Nothing (a null reference).
4. All data types and all reference types widen to the Object data type. This means you can convert any type
to Object without encountering a System.OverflowException error. However, if you convert between value
types and Object, Visual Basic performs operations called boxing and unboxing, which make execution
slower.
5. Object has no literal type character or identifier type character.
6. The corresponding type in the .NET Framework is the System.Object class.
8. UNIT II
Page 8
2.3.10 SByte Data Type
1. Holds signed8-bit (1-byte) integers that range in value from -128 through 127.It can be used to contain
integer values that do not require the full data width of Integer or even the half data width of Short to
save memory consumption.
2. The default value of SByte is 0.
3. The SByte data type is not part of the Common Language Specification (CLS), so CLS-compliant code
cannot consume a component that uses it.
4. The SByte data type widens to Short, Integer, Long, Decimal, Single, and Double. This means you can
convert SByte to any of these types without encountering a System.OverflowException error.
5. SByte has no literal type character or identifier type character.
6. The corresponding type in the .NET Framework is the System.SByte structure.
2.3.11 Short Data Type
1. Holds signed16-bit (2-byte) integers that range in value from -32,768 through 32,767.it can be used to
contain integer values that do not require the full data width of Integer to save memory consumption.
2. The default value of Short is 0.
3. The Short data type widens to Integer, Long, Decimal, Single, or Double. This means you can convert
Short to any one of these types without encountering a System.OverflowException error.
4. The literal type character S is used to the Short data type.
5. The corresponding type in the .NET Framework is the System.Int16 structure.
2.3.12 Single Data Type
1. Holds signed4-byte single-precision floating-point numbers ranging from negative values to positive
values. Single-precision numbers store an approximation of a real number.
2. It is used to contain floating-point values that do not require the full data width of Double. In some cases
the common language runtime might be able to pack your Single variables closely together and save
memory consumption.
3. The default value of Single is 0.
4. The Single data type widens to Double. This means you can convert Single to Double without
encountering a System.OverflowException error.
5. The floating-point data types do not have any internal representation of trailing 0 characters. For example,
they do not distinguish between 4.2000 and 4.2. Consequently, trailing 0 characters do not appear when
you display or print floating-point values.
6. Appending the literal type character F to a literal forces it to the Single data type. Appending the identifier
type character ! to any identifier forces it to Single.
7. The corresponding type in the .NET Framework is the System.Single structure.
2.3.13 String Data Type
1. Holds sequences of unsigned2-byte code points that range in value from 0 through 65535. Each code
point, or character code, represents a single Unicode character. A string can contain from 0 to
approximately two billion (2 ^ 31) Unicode characters.
2. Use the String data type to hold multiple characters without the array management overheadof Char(),
an array of Char elements.
9. UNIT II
Page 9
3. The default value of String is Nothing (a null reference). It is not the same as the empty string ("").
4. You must enclose a String literal within quotation marks (" "). If you must include a quotation mark as
one of the characters in the string, you use two contiguous quotation marks (""). The following example
illustrates this.
Dim h As String = "Hello"
5. Once you assign a string to a String variable, that string is immutable, which means you cannot change
its length or contents. When you alter a string in any way, Visual Basic creates a new string and
abandons the previous one. The String variable then points to the new string.
6. String cannot represent negative values. In any case, you should not use String to hold numeric values.
7. Appending the identifier type character $ to any identifier forces it to the String data type. String has no
literal type character. However, the compiler treats literals enclosedin quotation marks (" ") as String.
8. The corresponding type in the .NET Framework is the System.String class.
2.3.14 UInteger Data Type
1. Holds unsigned32-bit (4-byte) integers ranging in value from 0 through 4,294,967,295.The UInteger data
type provides the largest unsignedvalue in the most efficient data width.
2. The default value of UInteger is 0.
2.3.15 ULong Data Type
1. Holds unsigned64-bit (8-byte) integers. It can be used to contain binary data.
2. The default value of ULong is 0.
3. ULong is an unsignedtype, it cannot represent a negative number.
4. The ULong data type is not part of the Common Language Specification
5. The ULong data type widens to Decimal, Single, and Double. This means you can convert ULong to any
of these types without encountering a System.OverflowException error.
6. Appending the literal type characters UL to a literal forces it to the ULong data type. ULong has no
identifier type character.
7. The corresponding type in the .NET Framework is the System.UInt64 structure.
2.3.16 User-Defined Data Type
1. Holds data in a format you define. The Structure statement defines the format. It is used when you need
to combine various data types into a single unit, or when none of the elementary data types serve your
needs.
2. The default value of a structure data type consists of the combination of the default values of each of its
members.
2.3.17 UShort Data Type
1. Holds unsigned16-bit (2-byte) integers ranging in value from 0 through 65,535. We use the UShort data
type to contain binary data too large for Byte.
2. The default value of UShort is 0.
3. UShort is an unsignedtype; it cannot represent a negative number. LS Compliance.
10. UNIT II
Page 10
4. The UShort data type widens to Integer, UInteger, Long, ULong, Decimal, Single, and Double. This
means you can convert UShort to any of these types without encountering a System.OverflowException
error.
5. Appending the literal type characters US to a literal forces it to the UShort data type. UShort has no
identifier type character.
6. The corresponding type in the .NET Framework is the System.UInt16 structure.
Advantages of using data types
Specifying data types for all our variables is known as strong typing. It has several advantages:
It takes advantage of compiler type checking. This catches statements that can fail at run time due to
errors such as overflow. It also catches calls to methods on objects that do not support them.
It results in faster execution of our code.
2.4. Types
A data type is a value type if it holds the data within its own memory allocation. A reference type contains a
pointer to another memory location that holds the data.
2.4.1 Value Types
Value types include the following:
All numeric data types
Boolean, Char, and Date
All structures, even if their members are reference types
Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort,
UInteger, or ULong
2.4.2 Reference Types
Reference types include the following:
String
All arrays, even if their elements are value types
Class types, such as Form
NOTE:
We can assign either a reference type or a value type to a variable of the Object data type. An Object
variable always holds a pointer to the data, never the data itself. However, if we assign a value type to an
Object variable, it behaves as if it holds its own data.
In the .NET Framework, a structure is a value type and a class is a reference type. For this reason, value
types such as Char and Integer are implementedby .NET Framework structures, whereas reference types
such as Object and String are supported by .NET Framework classes. Note that every array is a reference
type, even if its members are value types, and that every structure is a value type, even if it has reference
type members.
2.5 DATA TYPE CONVERSION FUNCTIONS
Following functions are used to convert a value to a specific data type:-
Function name Return data type
CBool() Boolean Data Type
CByte() Byte Data Type
CChar() Char Data Type
CDate() Date Data Type
11. UNIT II
Page 11
CDbl() Double Data Type
CDec() Decimal Data Type
CInt() Integer Data Type
CLng() Long Data Type
CObj() Object Data Type
CSByte() SByte Data Type
CShort() Short Data Type
CSng() Single Data Type
CStr() String Data Type
CUInt() UInteger Data Type
CULng() ULong Data Type
CUShort() UShort Data Type
NOTE:
If the expression passed to the function is outside the range of the data type to which it is to be converted,
an OverflowException occurs.
When we convert a nonintegral value to an integral type, the integer conversion functions (CByte, CInt,
CLng, CSByte, CShort, CUInt, CULng, and CUShort) remove the fractional part and round the value to
the closest integer. If the fractional part is exactly 0.5, the integer conversion functions round it to the
nearest even integer. For example, 0.5 rounds to 0.
2.5.1 Widening and Narrowing Conversions
In type conversion the result of the conversion may exist within the range of the destination data type or not. A
widening conversion changes a value to a data type that can accommodate any possible value of the original data.
A narrowing conversion changes a value to a data type that might not be able to hold some of the possible values.
2.5.1.1 Widening Conversions
The table shows the standard 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
Any enumerated
type (Enum)
Its underlying integral type and any type to which the underlying
type widens
Char Char, String
Char array Char array, String
Any type Object
12. UNIT II
Page 12
NOTE:
By definition, every data type widens to itself.
Conversions from Integer, UInteger, Long, ULong, or Decimal to Single or Double might result in loss of
precision, but never in loss of magnitude. In this sense they do not incur information loss. Widening
conversions always succeedat run time and never incur data loss. You can always perform them
implicitly, whether the Option Strict Statement sets the type checking switch to On or to Off.
2.5.1.1 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 from any numeric type to any enumeratedtype (Enum)
Conversions in either direction between String and any numeric type, Boolean, or Date
Conversions from a data type or object type to a type derivedfrom it
Narrowing conversions do not always succeedat run time, and can fail or incur data loss. An error occurs if the
destination data type cannot receive the value being converted. For example, a numeric conversion can result in
an overflow. The compiler does not allow you to perform narrowing conversions implicitly unless the Option Strict
Statement sets the type checking switch to Off.
NOTE:
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 — if the convertedvalue is too large for the target type
2.5.2 CType Function
The CType Function is an alternative conversion function available in VB.NET which can be used for for any kind
of type conversion. It takes two arguments; first argument specifies value to be converted and second argument
specifies typename to which value is to be converted.
Dim Number As Long = 1000
Dim NewNumber As Single = CType (Number, Single)
2.5.3 TryCast Function
It is a type conversion function which is used for any kindof reference type conversion that does not throw an
exception. If an attempted conversion fails then CType throws InvalidCastException error which can adversely
affect the performance of application where as TryCast returns nothing insteadof having to handle a possible
exception.
Dim Number As Long = 1000
Dim NewNumber As Object = CType (Number, Object)
Summary:-
Keyword Data types Run-time failure
CType() Any data types Throws InvalidCastException
TryCast() Reference types only Returns Nothing
13. UNIT II
Page 13
2.4 OPTION STATEMENTS
2.4.1 OPTION EXPLICIT
Forces explicit declaration of all variables to be used in the program.
If used, the Option Explicit statement must appear before any other source code statements.
If we try to use an undeclared variable name, an error occurs at compile time.
If we do not specify Option Explicit in our code than by default Option Explicit is On.
Option Explicit On
Dim a As Integer
a = 10
b = 10 ' This assignment produces a COMPILER ERROR because variable is not declared and Option
Explicit is On.
2.4.2 OPTION STRICT
Visual Basic allows conversions of many data types to other data types. Data loss can occur when the
value of one data type is converted to a data type with less precision or smaller capacity. A run -time error
occurs if such a narrowing conversion fails. Option Strict ensures compile -time notification of these
narrowing conversions so that they can be avoided. It restricts implicit data type conversions to only
widening conversions.
If used, the Option Strict statement must appear before any other source code.
Because Option Strict On provides strong typing, prevents unintendedtype conversions with data loss
and improves performance, its use is strongly recommended. The compiler default is Option Strict Off if
we do not specify Option Strict in our code.
NOTE:
The compiler default is Option Strict Off if we do not specify Option Strict in our code.
2.4.3 OPTION COMPARE
This is used to specify the default comparison method to be used when needto compare string data’s.
Option Compare Binary sets the string comparison method to Binary. If used, the Option Compare
statement must appear in a file before any other source code statements.
The Option Compare statement specifies the string comparison method (Binary or Text) for a class,
module or structure.
If an Option Compare statement is not included, the default text comparison method is Binary.
2.5 IMPORTS STATEMENT
IMPORTS STATEMENT is used to import any namespace. After using IMPORTS statement all named
members of that namespace are available without qualification. For example:-
Imports System.Console
Module module1
Sub main()
Writleine("Hello")
End Sub
Each file can contain any number of Imports statements. Imports statements must be placed before any
declarations.
2.6 SCOPE IN VB.NET
The scope of a declared element is the set of all code that can refer to it without qualifying its name or making it
available through an Imports Statement. An element can have scope at one of the following levels:-
14. UNIT II
Page 14
2.6.1 BLOCK SCOPE
A block is a set of statements enclosedwithin initiating andterminating declaration statements, such as the
following:
Do and Loop
If and End If
Select and End Select
Try and End Try
While and End While
For Example:-
If n < 1291 Then
Dim cube As Integer
Cube = n ^ 3
End If
2.6.2 PROCEDURE SCOPE
An element declaredwithin a procedure is not available outside that procedure. Only the procedure that contains
the declaration can use it. Variables at this level are also known as local variables
Sub main()
Dim a As Integer
Writleine(a)
End Sub
2.6.3 MODULE SCOPE
Module level applies to modules, classes, and structures. We can declare elements at this level by placing the
declaration statement outside of any procedure or block but within the module, class, or structure.
2.6.4 NAMESPACE SCOPE
If we declare an element at module level using the Friend(Visual Basic) or Public (Visual Basic) keyword, it
becomes available to all procedures throughout the namespace in which the element is declared. With the
following alteration to the preceding example, the string variable strMsg can be referredto by code anywhere in
the namespace of its declaration.
Namespace scope includes nestednamespaces. An element available from within a namespace is also available
from within any namespace nestedinside that namespace.
If your project does not contain any Namespace Statements, everything in the project is in the same namespace.
In this case, namespace scope can be thought of as project scope. Public elements in a module, class, or
structure are also available to any project that references their project.
Level Description
Block scope Variable is available only within the code block in which it is declared
Procedure scope Variable is available to all code within the procedure in which it is declared
Module scope Variable is available to all code within the module, class, or structure in
which it is declared
Namespace
scope
Variable is available to all code in the namespace in which it is declared
15. UNIT II
Page 15
2.7 CHECKING DATA TYPES FUNCTIONS
Function Description
IsArray() An array of values, rather than a single value
IsDate() A Date Data Type (Visual Basic) value, or a string that can be interpretedas a date
and time value
IsDBNull() An object of type DBNull, which represents missing or nonexistent data
IsError () An exception object, which derives from Exception
IsNothing() Nothing (Visual Basic), that is, no object is currently assignedto the variable
IsNumeric() A number, or a string that can be interpreted as a number
IsReference() A reference type (such as a string, array, delegate, or class type)
2.8 Arrays
An array is a set of values that are logically relatedto each other, such as the number of students in each grade
in a grammar school.
An array allows you to refer to these relatedvalues by the same name and to use a number, called an index or
subscript, to tell them apart. The individual values are calledthe elements of the array. They are contiguous from
index 0 through the highest index value.
In contrast to an array, a variable containing a single value is called a scalar variable.
Dim students(6) As Integer
Dim values As Double() = {1, 2, 3, 4, 5, 6}
The array students in the preceding example contain 7 elements. The indexes of the elements range from 0
through 6. Having this array is simpler than declaring 7 different variables.
The following illustration shows the array students. For each element of the array:
The index of the element represents the grade (index 0 represents kindergarten).
The value containedin the element represents the number of students in that grade.
Elements of the "students" array
The following example shows how to refer to the first, second, and last element of the array students.
Dim kindergarten As Integer = students(0)
Dim firstGrade As Integer = students(1)
Dim sixthGrade As Integer = students(6)
MsgBox("Students in kindergarten = " & CStr(kindergarten))
MsgBox("Students in first grade = " & CStr(firstGrade))
MsgBox("Students in sixth grade = " & CStr(sixthGrade))
2.8.1 Array Dimensions
The array students in the preceding example uses one index and is said to be one -dimensional. An array that
uses more than one index or subscript is called multidimensional.A dimension is a direction in which you can
vary the specification of an array's elements. An array that holds the sales total for each day of the month has
one dimension (the day of the month). An array that holds the sales total by department for each day of the
16. UNIT II
Page 16
month has two dimensions (the department number and the day of the month). The number of dimensions an
array has is called its rank.
You specify an element of an array by supplying an index or subscript for each of its dimensions. The elements
are contiguous along each dimension from index 0 through the highest index for that dimension.
The following illustrations show the conceptual structure of arrays with different ranks. Each element in the
illustrations shows the index values that access it. For example, you can access the first element of the second
row of the two-dimensional array by specifying indexes (1, 0).
One-dimensional array
Two-dimensional array
Three-dimensional array
One Dimension
Many arrays have only one dimension, such as the number of people of each age. The only requirement to specify
an element is the age for which that element holds the count. Therefore, such an array uses only one index. The
following example declares a variable to hold a one-dimensional array of age counts for ages 0 through 120.
To declare a one-dimensional array variable, add one pair of parentheses after the variable name.
Dim cargoWeights() As Double
Dim ageCounts(120) As UInteger
Two Dimensions
17. UNIT II
Page 17
Some arrays have two dimensions, such as the number of offices on each floor of each building on a campus. The
specification of an element requires both the building number and the floor, and each element holds the count for
that combination of building and floor. Therefore, such an array uses two indexes. The following example declares
a variable to hold a two-dimensional array of office counts, for buildings 0 through 40 and floors 0 through 5.
To declare a multidimensional array variable, add one pair of parentheses after the variable name andplace
commas inside the parentheses to separate the dimensions.
Dim atmospherePressures(,,,) As Short
Dim officeCounts(40, 5) As Byte
NOTE: - A two-dimensional array is also called a rectangular array.
Three Dimensions
A few arrays have three dimensions, such as values in three -dimensional space. Such an array uses three
indexes, which in this case represent the x, y, and z coordinates of physical space. The following example declares
a variable to hold a three-dimensional array of air temperatures at various points in a three -dimensional volume.
Dim airTemperatures(99, 99, 24) As Single
More than Three Dimensions
Although an array can have as many as 32 dimensions, i t is rare to have more than three.Suppose you want to
track sales amounts for every day of the present month. You might declare a one -dimensional array with 31
elements, one for each day of the month, as the following example shows.
Dim salesAmounts(30) As Double
Now suppose you want to track the same information not only for every day of a month but also for every month
of the year. You might declare a two-dimensional array with 12 rows (for the months) and 31 columns (for the
days), as the following example shows.
Dim salesAmounts(11, 30) As Double
Now suppose you decide to have your array hold information for more than one year. If you want to track sales
amounts for 5 years, you could declare a three -dimensional array with 5 layers, 12 rows, and 31 columns, as the
following example shows.
Dim salesAmounts(4, 11, 30) As Double
Note that, because each index varies from 0 to its maximum, each dimension of salesAmounts is declared as one
less than the required length for that dimension. Note also that the size of the array increases with each new
dimension. The three sizes in the preceding examples are 31, 372, and 1,860 elements respectively.
JAGGED ARRAY
Another kind of array is one which holds other arrays as elements. This is known as an array of arrays or a
jagged array. A jagged array can be either one -dimensional or multidimensional, and so can its elements.
Sometimes the data structure in your application is two-dimensional but not rectangular. For example, you might
have an array of months, each element of which is an array of days. Since different months have different
numbers of days, the elements do not form a rectangular two-dimensional array. In such a case, you can use a
jagged array insteadof a multidimensional array.
NOTE:- Zero-Length Arrays
An array with no elements is also called a zero-length array. A variable holding a zero-length array does not have
the value Nothing. To create an array that has no elements, declare one of the array's di mensions to be -1, as
shown in the following example.
Dim twoDimensionalStrings(-1, 3) As String
You might needto create a zero-length array under the following circumstances:
18. UNIT II
Page 18
Your code needs to access members of the Array class, such as Length or Rank, or call a Visual Basic
function such as UBound, without risking a NullReferenceException exception.
You want to keepthe consuming code simpler by not having to check for Nothing as a special case.
Your code interacts with an application programming interface (API) that requires you to pass a zero-length
array to one or more procedures, or that returns a zero-length array from one or more procedures.
2.9 TYPES OF PROCEDURES
Visual Basic uses several types of procedures:
Sub Procedures perform actions but do not return a value to the calling code.
Event-handling procedures are Sub procedures that execute in response to an event raised by user action or by
an occurrence in a program.
Function Procedures return a value to the calling code. They can perform other actions before returning.
Property Procedures return and assign values of properties on objects or modules.
Operator Procedures define the behavior of a standard operator when one or both of the operands is a newly-
defined class or structure.
Generic Procedures in Visual Basic define one or more type parameters in addition to their normal parameters,
so the calling code can pass specific data types each time it makes a call.
SUB PROCEDURES
A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End Sub statements. The Sub
procedure performs a task and then returns control to the calling code, but it does not return a value to the calling
code.
You can define a Sub procedure in modules, classes, and structures. By default, it is Public, which means you can
call it from anywhere in your application that has access to the module, class, or structure in which you defined it.
The syntax for each parameter in the parameter list is as follows:
[Optional] [ByVal | ByRef] [ParamArray] parametername As datatype
If the parameter is optional, you must also supply a default value as part of its declaration. The syntax for
specifying a default value is as follows:
Optional [ByVal | ByRef] parametername As datatype = defaultvalue
The syntax for a call to a Sub procedure is as follows:
[Call] subname[(argumentlist)]
Sub tellOperator(ByVal task As String)
Dim stamp As Date
stamp = TimeOfDay()
MsgBox("Starting " & task & " at " & CStr(stamp))
End Sub
Call tellOperator("file update")
19. UNIT II
Page 19
FUNCTION PROCEDURES
A Function procedure is a series of Visual Basic statements enclosed by the Function and End Function statements.
The Function procedure performs a task and then returns control to the calling code. When it returns control, it also
returns a value to the calling code.
Each time the procedure is called, its statements run, starting with the first executable statement after the Function
statement and ending with the first End Function, Exit Function, or Return statement encountered.
You can define a Function procedure in a module, class, or structure. It is Public by default, which means you can
call it from anywhere in your application that has access to the module, class, or structure in which you defined it.
DECLARATION SYNTAX
[modifiers] Function functionname[(parameterlist)] As returntype
'Statements of the Function procedure
End Function
Function findSqrt(ByVal radicand As Single) As Single
End Function
RETURNING VALUES
The value a Function procedure sends back to the calling code is called its return value. The procedure returns this
value in one of two ways:
It assigns a value to its own function name in one or more statements of the procedure. Control does not
return to the calling program until an Exit Function or End Function statement is executed.
Function functionname[(parameterlist)] As returntype
functionname = expression
'When control returns to the calling code, expression is the return value.
End Function
It uses the Return statement to specify the return value, and returns control immediately to the calling
program.
Function functionname[(parameterlist)] As returntype
Returnexpression
End Function
The syntax for a call to a Function procedure is as follows:
lvalue = functionname[(argumentlist)]
NOTE:
1. If a parameter is defined as Optional (Visual Basic), you can either include it in the argument list or omit it. If
you omit it, the procedure uses the default value defined for that parameter. If you omit an argument for an
Optional parameter and there is another parameter after it in the parameter list, you can mark the place of the
omitted argument by an extra comma in the argument list.
20. UNIT II
Page 20
To define a procedure parameter
Precede the parameter name with ByVal or ByRef to specify the passing mechanism.
2.10 EXCEPTION HANDLING
Errors
Exceptions
TYPES OF EXCEPTION HANDLING
Unstructured Exception Handling
Structured Exception Handling
UNSTRUCTURED EXCEPTION HANDLING
Syntax:
On Error {Goto [line|0|-1] Resume Next}
GoToline
Enables the error-handling routine that starts at the line specified in the required line argument. The line
argument is any line label or line number. If a run-time error occurs, control branches to the specified line,
making the error handler active. The specified line must be in the same procedure as the On Error
statement, or a compile-time error will occur.
GoTo 0
Disables enabled error handler in the current procedure and resets it to Nothing.
GoTo -1
Disables enabled exception in the current procedure and resets it to Nothing.
Resume Next
Specifies that when a run-time error occurs, control goes to the statement immediately following the
statement where the error occurred, and execution continues from that point. Use this form rather than On
Error GoTo when accessing objects
Example:
On Error GoTo handler
Dim a, b, c As Integer
a = 1
b = 0
c = a / b
Exit Sub
handler:
System.Console.WriteLine("Error")
System.Console.ReadLine()
21. UNIT II
Page 21
Example:
On Error Resume Next
Dim a, b, c As Integer
a = 1
b = 0
c = a / b
System.Console.WriteLine("program completed")
System.Console.ReadLine()
Exit Sub
Example:
On Error GoTo handler
Dim a, b, c As Integer
a = 1
b = 0
c = a / b
Exit Sub
handler:
System.Console.WriteLine("Error Number(Err.Number): " & Err.Number &
vbCrLf)
System.Console.WriteLine("Error Description(Err.Description): " &
Err.Description & vbCrLf)
System.Console.WriteLine("Error Source File(Err.Source): " &
Err.Source & vbCrLf)
System.Console.WriteLine(Err.GetException)
System.Console.ReadLine()
22. UNIT II
Page 22
Example:
On Error GoTo handler
Dim a, b, c As Integer
a = 1
b = 0
c = a / b
handler:
If TypeOf Err.GetException() Is OverflowException Then
System.Console.WriteLine("overflow error")
End If
System.Console.ReadLine()
Exit Sub
Example:
Sub Main()
On Error GoTo -1
Dim a, b, c As Integer
a = 1
b = 0
c = a / b
handler:
If TypeOf Err.GetException() Is OverflowException Then
System.Console.WriteLine("overflow error")
End If
System.Console.ReadLine()
Exit Sub
23. UNIT II
Page 23
Example:
On Error GoTo handler
Dim a, b, c As Integer
a = 1
b = 0
Err.Raise(6)
handler:
System.Console.WriteLine(Err.Description)
System.Console.ReadLine()
Exit Sub
24. UNIT II
Page 24
STRUCTURED EXCEPTION HANDLING
Try
[try statements]
Exit Try
Catch exception As Type
[catch statemnets]
Exit Try
Catch exception2 As Type
[catch statemnets]
Finally
[Finally statments]
End Try
Example:
Try
Dim a, b, c As Integer
a = 1
b = 0
c = a / b
Catch exception1 As Exception
System.Console.WriteLine(exception1.Message & vbCrLf)
System.Console.WriteLine(exception1.ToString)
Exit Try
End Try
Example:
Try
Dim a, b, c As Integer
a = 1
b = 0
c = a / b
Catch exception1 As System.OverflowException
System.Console.WriteLine(exception1.Message & vbCrLf)
25. UNIT II
Page 25
System.Console.WriteLine(exception1.ToString)
Exit Try
Catch exception2 As Exception
System.Console.WriteLine(exception2.Message & vbCrLf)
System.Console.WriteLine(exception2.ToString)
Exit Try
Finally
System.Console.WriteLine(vbCrLf & "program completed")
End Try
End Try
Example:
Try
Throw New OverflowException
Catch exception1 As System.OverflowException
System.Console.WriteLine(exception1.Message & vbCrLf)
Exit Try
26. UNIT II
Page 26
2.11 OBJECT ORIENTED PROGRAMMING FEATURES
FOUR PILLARS OF OOPS
Encapsulation
Polymorphism
Abstraction
Inheritance
ENCAPSULATION
It can be defined as the separation between implementation and interface (i.e., data and function). It can be defined
as wrapping up of data into single unit. It is also called as data hiding. Encapsulation is implemented using classes
and structures.
CLASSES
Classes are the heart and soul of an object-oriented language. It is the user defined data type which can bind the
data and function into single unit. It provides the template framework which can have data members and methods.
It also consist some special procedures called as constructors and destructors. We can also create properties,
procedures and classes in it.
[Public Private Protected Friend Protected Friend]
[MustInherit Partial NotInheritable] Classname
[Inherits] classname
[Implements] interfacename, interfacename
Public Class Line
Private ID As Integer
Public Name As String
Private mstrFileName As String
'NOTE: properties represents the charcterstics of an objet (Class). It uses
Set and Get method to manipulate internal values
Property EMPID() As Integer
Get
Return ID
End Get
Set(ByVal Value As Integer)
ID = Value
End Set
End Property
ReadOnly Property EmpName() As String
Get
Return Name
End Get
End Property
27. UNIT II
Page 27
WriteOnly Property FileName() As String
Set(ByVal Value As String)
mstrFileName = Value
End Set
End Property
Function display() As Integer
Return mstrLine
End Function
Sub abc(ByVal a As Integer)
Console.WriteLine(mstrLine)
End Sub
End Class
Sub Main()
Dim oLine As Line = New Line()
'Or Dim oLine As New Line()
System.Console.WriteLine(Obj.display())
End Sub
DIFFERENCE BETWWEN CONSTRUCTORS AND METHODS
Constructors Methods
No return type May have return type
Same name as that of class. In VB.NET it
is Sub New()
End Sub block
Have different name
Called implicitly Called explicitly
STRUCTURES
It is the user defined data type like classes which can bind the data and function into single unit. It provides the
template framework which can have data members and methods. You cannot inherit from a structure; structures
should be used only for objects that do not need to be extended. We can use structures when the object you wish to
create has a small instance size.
Structure a
[Public Private Protected Friend Protected Friend]
[Partial]
[Implements interfacename]
End Structure
Structure abc
Private id As Integer
28. UNIT II
Page 28
Public name As String
Sub display(ByVal id As Integer)
Console.WriteLine(id)
End Sub
End Structure
Sub Main()
Dim obj As New abc
obj.name = "BCA"
Console.WriteLine(obj.name)
obj. display(1)
End Sub
SIMILARITIES BETWEEN STRUCTURES AND CLASSES
Structures and classes are similar in the following respects:
Both are container types, meaning that they contain other types as members.
Both have members, which can include constructors, methods, properties, fields, constants, enumerations.
Both can implement interfaces.
DIFFERENCE BETWEEN STRUCTURES AND CLASSES
STRUCTURES CLASSES
Value type. Structures use stack allocation Reference type. Classes use heap
allocation.
Cannot have default parameter-less
constructors ans destructor.
Can have default constructors and
destructor.
Cannot inherit any class or structures. That
is why structures are also called as sealed
class. So it cannot override finalize
method.
Can inherit any class or structures.
All structure elements are Public by default class variables and constants are Private by
default
structure must have at least one nonshared
variable or nonshared, noncustom event
element
class can be completely empty
SHARED MEMBERS IN VISUAL BASIC
Shared members are properties, procedures, and fields that are shared by all instances of a class or structure. Some
programming languages refer to such items as static members.
29. UNIT II
Page 29
SHARED FIELDS AND PROPERTIES
Shared fields and properties are useful when you have information that is part of a class but is not specific to any
one instance of a class. When you change the value of a shared field and property, you change the value associated
with the class and all instances of the class.
On the other hand, changing the value of a non-shared field or property associated with any one instance does not
affect the value of that field or property in other instances of the class. Non-shared fields and properties exist
independently for each instance of a class.
In this way, shared fields and properties behave like global variables that can be accessed only from instances of a
class, or with qualification of the class name. Without shared fields and properties, you would need to use module-
level variables to achieve the same effect. However, module-level variables can make your classes difficult to
understand and maintain. Furthermore, using module-level variables in this way violates the concept of
encapsulation that classes represent.
SHARED PROCEDURES
Shared procedures are class methods that are not associated with a specific instance of a class. Shared procedures
and properties do not have access to instances of the class.
Public Class Item
Public Shared Count As Integer = 1
Public Shared Sub ShareMethod()
MsgBox("Current value of Count: " & Count)
End Sub
Public Sub New(ByVal Name As String)
' Use Count to initialize SerialNumber.
Me.SerialNumber = Count
Me.Name = Name
' Increment the shared variable
Count += 1
End Sub
Public SerialNumber As Integer
Public Name As String
Public Sub InstanceMethod()
MsgBox("Information in the first object: " & _
Me.SerialNumber & vbTab & Me.Name)
End Sub
End Class
Sub TestShared()
' Create two instances of the class.
Dim part1 As New Item("keyboard")
Dim part2 As New Item("monitor")
part1.InstanceMethod()
part2.InstanceMethod()
Item.ShareMethod()
30. UNIT II
Page 30
End Sub
CONSTRUCTORS & DESTRUCTORS
A Constructor is a special function which is called automatically when a class is created. A Destructor is a
special function which is called automatically when a class is destroyed. In VB.NET,
Class Dog
'The age variable
Private Age As Integer
Public Sub New()
'This constructor block
Console.Writeline("Dog is Created With Age Zero")
Age = 0
End Sub
Public Sub New(ByVal val As Integer)
Console.Writeline("Dog is Created With Age " +
Convert.ToString(val))
Age = val
End Sub
Protected Overrides Sub Finalize()
'This destructor block
Console.Writeline("Dog is Destroyed")
End Sub
'The Main Function
End Class
ABSTRACTION
Public: Declaring a class as Public means you can "see" and instantiate this class in any other classes or
subroutines within the same assembly. If you've compiled it into a DLL, referencing assemblies can see it,
as well. Declaring a Public Sub / Function or Property means that when its container class is instantiated, the
consumer can also see the method or property.
Private: Private limits the visibility to a scope. Declaring a private class within a class means that "sub-
class" can't be seen from outside of the class. This is also true for methods and properties - they can be seen
within the class, but not to any consumers or inheritors.
Protected: Protected members act as private members in class. This will more likely apply to methods and
properties; they won't necessarily be seen outside of the class in which they're declared. However, if a class
inherits the container class, that inheritor can see the protected members.
Friend: This applies to classes, methods, and properties. They can be seen within the assembly, but not to
any referencing assemblies or even inheritors. (This is the equivalent of "internal" in C#)
31. UNIT II
Page 31
Protected Friend: This is what it seems; classes, methods, and properties declared with this can be seen
both within the assembly, as well as by inheritors. They cannot be seen from referencing assemblies. (This
is "protected internal" in C#)
POLYMORPHISM
Public Overloads Sub Add(ByVal A As Integer, ByVal B As Integer)
Console.Writeline("Adding Integers: " + Convert.ToString(a + b))
End Sub
Public Overloads Sub Add(ByVal A As String, ByVal B As String)
Console.Writeline("Adding Strings: " + a + b)
End Sub
INHERITANCE
Inheritance is the property in which, a derived class acquires the attributes of its base class. In simple terms, you
can create or 'inherit' your own class (derived class), using an existing class (base class). You can use the Inherits
keyword for this.
Class Human
'This is something that all humans do
Public Sub Walk()
Console.Writeline("Walking")
End Sub
End Class
Class Programmer
Inherits Human
Public Sub StealCode()
Console.Writeline("Stealing code")
End Sub
End Class
SOME IMPORTANT KEYWORDS
MustInherit
The MustInherit keyword specifies that a class cannot be instantiated and can be used only as a base
class. i.e., if you declare our Human class as "MustInherit Class Human", then you can't create
objects of type Human without inheriting it.
NotInheritable
The NotInheritable keyword specifies that a class cannot be inherited. I.e., if you specify
'NotInheritable Class Human', no derived classes can be made from the Human class.
The Overridable keyword is used to mark a function as overridable.
32. UNIT II
Page 32
The keyword Overrides is used to mark that a function is overriding some base class function.
Class Human
'Speak() is declared Overridable
Public Overridable Sub Speak()
Console.Writeline("Speaking")
End Sub
End Class
Class Indian
Inherits Human
Public Overrides Sub Speak()
Console.Writeline("Speaking Hindi")
End Sub
End Class
INTERFACES
Interfaces define the properties, methods, and events that classes can implement. They also provide another way of
implementing polymorphism. Through interfaces, we specify methods that a component must implement without
actually specifying how the method is implemented. We just specify the methods in an interface and leave it to the
class to implement those methods. Visual Basic .NET does not support multiple inheritance directly but using
interfaces we can achieve multiple inheritance.
We use the Interface keyword to create an interface and implements keyword to implement the interface. Once you
create an interface you need to implement all the methods specified in that interface. The following code
demonstrates the use of interface.
[ Public | Private | Protected | Friend | Protected Friend ] _
[ Shadows ] Interface name
[ Inherits interfacename[, interfacename ]]
[ [ Default ] Property proname ]
[ Function memberame ]
[ Sub memberame ]
[ Event memberame ]
End Interface
Example:
Public Interface Test
'creating an Interface named Test
Sub disp()
Function Multiply() As Double
'specifying two methods in an interface
End Interface
Public Class One
Implements Test
'implementing interface in class One
33. UNIT II
Page 33
Public i As Double = 12
Public j As Double = 12.17
Sub disp() Implements Test.disp
'implementing the method specified in interface
WriteLine("sum of i+j is" & i + j)
Read()
End Sub
Public Function multiply() As Double Implements Test.Multiply
'implementing the method specified in interface
WriteLine(i * j)
Read()
End Function
End Class
Example:
Interface Interface1
Sub sub1(ByVal i As Integer)
End Interface
Interface Interface2
Inherits Interface1 ' Demonstrates interface inheritance.
Sub M1(ByVal y As Integer)
ReadOnly Property Num() As Integer
End Interface
Public Class ImplementationClass1
Implements Interface1
Sub Sub1(ByVal i As Integer) Implements Interface1.Sub1
' Place code here to implement this method.
End Sub
End Class
Public Class ImplementationClass2
Implements Interface2
Dim INum As Integer = 0
Sub sub1(ByVal i As Integer) Implements Interface2.Sub1
' Place code here that implements this method.
End Sub
Sub M1(ByVal x As Integer) Implements Interface2.M1
' Place code here to implement this method.
End Sub
ReadOnly Property Num() As Integer Implements _
Interface2.Num
Get
Num = INum
End Get
End Property
End Class
34. UNIT II
Page 34
ADO.NET –Working with databases
Applications need to communicate with the database for the following tasks:
Retrieving the data stored in the database and presenting it in a user friendly
format
Updating the database that is inserting, modifying and deleting data
Hence ADO.NET is a model used by .NET applications to communicate with the
database.
Every organization maintains data pertaining to its business, employees and clients.
Therefore most applications require some form of data access.VB.net provides one of
the most powerful and easy front end development environments for database
management. In actual production environment database is installed on one of the
computers in the network .The application is installed on many clients and all the
clients access the same database installed on the server. It is the applications
responsibility to preset the data to the user and process it. The machine on which the
database is there is known as the server and the machines on which the applications
are there are known as clients.
Evolution of ADO.NET
ODBC-(pronounced as separate letters) Short for Open DataBase Connectivity, a
standard database access method developed by the SQL Access group in 1992. The
goal of ODBC is to make it possible to access any data from any application,
regardless of which database management system (DBMS) is handling the data.
ODBC manages this by inserting a middle layer, called a database driver , between an
application and the DBMS. The purpose of this layer is to translate the application's
data queries into commands that the DBMS understands. For this to work, both the
application and the DBMS must be ODBC-compliant -- that is, the application must be
capable of issuing ODBC commands and the DBMS must be capable of responding to
them. ODBC is a database interface used to interact with database from a
programming language through its functions. The functions of ODBC include adding,
modifying, deleting data and obtaining details about the database, tables, view and
indexes. So ODBC provides access to any data source, either local or remote as long
as appropriate ODBC driver is available.
Microsoft followed a strategy called Universal Data Access. The UDA strategy of
Microsoft is designed to provide access to all types of data through a single data access
model. Hence Microsoft introduced oledb as an enhancement odbc .OLEDB includes
35. UNIT II
Page 35
access to data other than SQL data while ODBC is an industry standard way to
connect to SQL databases like oracle, db2, access etc:
Since OLEDB is a C++ API, it is not directly accessible to many development
environments. For this environment Microsoft has provided a set of programmable
objects known as the Activex data objects that allow access to OLEDB.
Keeping in sync with universal data access strategy, Microsoft has released ADO.NET
as the data access technology while working in the .NET platform. ADO. NET is the
primarly library for building solutions within the .NET framework while COM based
applications still use ADO as data access tool
The first data access model (DAO was created for local data bases).Next was RDO
(Remote Data Object) and ADO (Activex Data abject) which were designed for client
server architecture. But ADO was a connected data access technology using only
connected architecture
Overview of ADO.NET
Visual Studio .NET provides support for a new generation of data access technology
known as ADO.NET.ADO.NET typically reduce development time ,simplify code and
provide excellent performance.
ADO.NET provides user to retrieve data from database using 2 architectures
1. Connected Architecture
2. Disconnected Architecture
Connected Architecture
A Connection to the database system is made and then interacted with it through SQL
queries using the connection. The application stays connected to the DB system even
when it is not using DB services. The connection remains open until the application is
closed.
Advantage
1) Gives the updated information to client immediately
2) Suitable where data change is frequent.
Limitation
1) Leaving the connection open for lifetime time of the application Commonly
wastes valuable and expensive database resources, as most of the time
36. UNIT II
Page 36
applications only query and view the persistent data ,so with more number of
connections, performance degrades.
2) Since connection is maintained for long time security and network traffic is a
major issue.
3) Not suitable for websites since applications which are on the web need to be
easily scalable since traffic to a website can go up by any order of magnitude in a
very short period
Disconnected architecture
ADO.Net solves this problem by managing a local buffer of persistent data called a
data set. Application automatically connects to the database server when it needs to
run a query and then disconnects immediately after getting the result back and storing
it in the dataset.
Dataset is disconnected In-Memory representation of the database. The dataset object
stores the tables, their relationship and their different constraints. The user can perform
operations like update, insert and delete on this dataset locally, and the changes made
to the dataset are applied to the actual database as a batch when needed. This greatly
reduces network traffic and results in better performance.
Advantage
1) Database security and network security problem of connected architecture is
resolved.
Limitation
1) If data is updated frequently in database, dataset have to be refilled again and again
i.e real time data not available.
Features of ADO.NET are described below
Data Access Styles
ADO.NET allows us to work with connected as well as disconnected Architecture.
Applications connect to the database only when retrieving and updating data. After
37. UNIT II
Page 37
that connection is closed. When the database needs to be updated the connection is re
established. ADO.NET uses data reader to work in the connected mode and datasets to
work in the disconnected mode.
Data is cached in datasets
DataSet is a disconnected in memory representation of data. It can be considered as a
local copy of the relevant portions of the database. The dataset is persisted in memory
and data in it can be manipulated and updated independent of the database. When the
use of dataset is finished, changes can be made back to the central database for
updating. ADO.NET supports scalability by working with datasets. Operations are
performed in the set instead of database, so resources are saved. The most common
task with database is to retrieve data and do some kind of processing with it. In most
of the real life situations, applications require data from multiple tables. Typical
example would be to retrieve the records in the orders table for a particular customer
along with the customer information in Customers table. Since it is not possible to go
back to the database each time the application needs to process the next record or
related records so dataset acts as the temporary store of records. So dataset acts like a
virtual data store and it can include information about the relationships between those
tables and constraints on what data the tables can contain
Data Sets are independent of data Sources
Datasets act as the cache for data retrieved from a database.The dataset doesn’t have
any actual relationship with the database.
Data transfer in XML format
Data is transferred from a database into a dataset and from the dataset to another
component by using XML. XML is an industry standard format .This means that your
application data components can exchange data with any other component in any other
application as long as the component understands XML.We can use XML as a data
source and store data from it in a dataset. Knowledge of XML is not required.
Interaction through commands
All operations are performed using commands. A data command can be a SQL
statement or a stored procedure. We can retrieve, insert, delete or modify data from a
database using commands.
ADO.NET Architecture
ADO.NET is a collection of classes, interfaces, structures and enumerated types that
manage data access from relational data stores within the .NET framework.
38. UNIT II
Page 38
Two ways we can access :
Either through dataset or data reader Object
Using dataset: Data is catched in a dataset and application can access the data from
the dataset.
Using a data reader: It uses the connection object to connect and command object to
retrieve data. It provides data only in read only and forward only mode.
The ADO .NET provides two central components for data access and data
manipulation. i.e Dataset and .NET Data provider
Data Providers
The .Net Framework includes mainly two Data Providers for ADO.NET. They are the
Microsoft SQL Server Data Provider (for Microsoft sql server 7.0 or later)
OLEDB Data Provider. (for data sources exposed using oledb)
Data Providers model in the ADO.NET is a set of 4 components. They are
Connection Object, Command Object , DataReader Object and DataAdapter
Object.
39. UNIT II
Page 39
1) Connection Object provides physical connection to the Data Source.
The Connection Object connect to the specified Data Source and open a
connection between the application and the Data Source, depends on the
parameter specified in the Connection String . When the connection is
established, SQL Commands will execute with the help of the Connection Object
and retrieve or manipulate data in the Data Source. A connection can be created
and managed using
SqlConnection object
OLEDB uses the OleDbConnection Object.
Dim conn As New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;Data
source=C:Documents and SettingskanikamDesktopPUBS.mdb")
Or
Dim conn As New OleDbConnection
conn.ConnectionString= Provider=Microsoft.JET.OLEDB.4.0;Data
source=C:Documents and SettingskanikamDesktopPUBS.mdb"
conn.open()
2) Command Object uses to perform SQL statement like read, add, update, and delete
records in a data source. ADO .NET provides the OleDbCommand or SqiCommand
class to perform these database operations. The command class must mater; the
connection class-. For example, if you are using a SqlConnection object to-
communicate with a SQL Server, you must also use commands that derive from the
SqiCommand class. The Command Object requires an instance of a Connection
Object for executing the SQL statements . In order to retrieve a result set or
execute an SQL statement against a Data Source , first you have to create a
Connection Object and open a connection to the Data Source specified in the
connection string. The Command Object has a property called CommandText ,
which contains a String value that represents the command that will be executed
against the Data Source. Once a command object has been set up, it can be
executed using any of the following methods:
40. UNIT II
Page 40
A. The ExecuteNonQuery() is one of the most frequently used method in
SqlCommand Object, and is used for executing statements that do not return
result sets (ie. statements like insert data , update data etc.)
B. The ExecuteScalar() in SqlCommand Object is using for retrieve a single
value from Database after the execution of the SQL Statement. The
executeScalar() executes SQL statements as well as Stored Procedure and
returned a scalar value on first column of first row in the returned Result Set.
If the Result Set contains more than one columns or rows , it will take only the
value of first column of the first row, and all other values will ignore. If the
Result Set is empty it will return a NULL reference.
It is very useful to use with aggregate functions like Count(*) or Sum() etc.
When compare to ExecuteReader() , ExecuteScalar() uses fewer System
resources.
C. The ExecuteReader() in VB.net SqlCommand Object sends the SQL
statements to the Connection Object and populate a SqlDataReader Object
based on the SQL statement.
The SqlDataReader Object is a stream-based , forward-only, read-only
retrieval of query results from the Data Source. The SqlDataReader cannot
be created directly from code, they can created only by calling the
ExecuteReader method of a C# Command Object.
D. The ExecuteXMLReader executes the command and returns a
XMLDataReader Object, which can be used to read the results one row at a time.
Dim mycomm As New OleDbCommand
Dim statement As String
statement = "select Author from publisher"
mycomm.Connection = conn
mycomm.CommandText = statement
Dim reader As OleDbDataReader
reader = mycomm.ExecuteReader()
3. DataReader Object(For Connected Architecture) is a stream-based , forward-
only, read-only retrieval of query results from the Data Source. The DataReader
Object provides a connection oriented data access to the Data Sources. It helps to
increase application performance and reduce system overhead because only one
row at a time is ever in memory. The DataReader is an abstract class and cannot be
used in an application. Instead, you have to use the SqlDataReader or the
41. UNIT II
Page 41
OleDbDataReader object, depending on the database you are connected to.
ExecuteReader returns a DataReader object
Dim reader As OleDbDataReader
reader = mycomm.ExecuteReader()
A Connection Object can contain only one DataReader at a time and the connection
in the DataReader remains open, also it cannot be used for any other purpose while
data is being accessed. When we started to read from a DataReader it should always be
open and positioned prior to the first record. The Read() method in the DataReader is
used to read the rows from DataReader and it always moves forward to a new valid
row, if any row exist.. Read method returns true if there are more rows that can be
fetched, otherwise false. You should always call the close method when you have finished
using the DataReader object by using reader. Close()
While (reader.Read())
MessageBox.Show(reader.GetValue(0))
End While
GetString() method is also used access the value of a column in the returned row
For example reader.Read();
Str=reader.GetString(1)
4. DataAdapter Object(Acts as an interface For Disconnected Architecture) ,
which populate a Dataset Object with results from a Data Source .
DataAdapter is a part of the ADO.NET Data Provider. DataAdapter provides
the communication between the Dataset and the Datasource. We can use the
DataAdapter in combination with the DataSet Object. DataAdapter provides this
combination by mapping Fill method, which changes the data in the DataSet to
match the data in the data source, and Update, which changes the data in the data
source to match the data in the DataSet. That is, these two objects combine to
enable both data access and data manipulation capabilities.
The DataAdapter can perform Select , Insert , Update and Delete SQL
operations in the Data Source. The Insert , Update and Delete SQL operations ,
42. UNIT II
Page 42
we are using the continuation of the Select command perform by the
DataAdapter.
The SelectCommand property of the DataAdapter is a Command Object that
retrieves data from the data source. The InsertCommand , UpdateCommand ,
and DeleteCommand properties of the DataAdapter are Command objects that
manage updates to the data in the data source according to modifications made to
the data in the DataSet.
Dim conn As New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;Data
source=C:Documents and SettingskanikamDesktopPUBS.mdb")
Dim mycomm As New OleDbCommand
Dim statement As String
statement = "select Author from publisher"
mycomm.Connection = conn
mycomm.CommandText = statement
Dim titlesDA as OledbDataAdapter= New OledbDataAdapter()
titlesDA.SelectCommand=mycomm
Dim titlesDS As DataSet=New DataSet()
TitlesDA.Fill(titlesDS,”publisher”)
Conn.close
Updating a database using DataSetand DataAdapter
The update method of the. Datadapter. is. called to resolve changes from A
DataSet back to the the data source, the Update method, like the Fill method
takes as arguments an instance of a DataSet and an optional DataTable object
or DataTable_name. The DataSet instance is the DataSet tha contains the
changes that have been made to the DataTable and DataTable identifies the table
from which to retrieve the changes When update method is called the DataAdapter
analyzes the changes that have been made and executes the appropriate insert,update
or delete command.
TitlesDA.Update(titlesDS)
v
47. UNIT II
Page 47
.
A DATABASE CAN BE CREATED USING TWO KIND OF ARCHITECTURE:-
(a.) IN CONNECTED ARCHITECTURE
(b.) IN DISCONNECTED ARCHITECTURE
Steps to create Database connection (MS-Access)
You CAN CONNECT YOUR WINDOW APPLICATION WITH MS-Access DATABASE THROUGH SERVER EXPLORER. FOR
THAT GO TO VIEW->THEN SERVER EXPLORER->Select DATA CONNECTION->RIGHT CLICK->SELECT ADD
CONNECTION WHICH WILL OPEN A WIZARD->CHOOSE DATASOURCE TYPE->CHOOSE MS-ACCESS DATABASE FILE-
>CHECK FOR TESTING CONNECTION WITH TEST CONNECTION OPTION BUTTON.
A.) EXAMPLE APPLICATION FOR ACCESSING THE MS-ACCESS DATABASE USING CONNECTED
ARCHITECTURE:-
48. UNIT II
Page 48
Imports System.Data.OleDb
Public Class Form1
Public i As Integer = 0
Private Sub Form1 _Load (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim con As New OleDbConnection
'Fetch the connection string from properties of your database. Go to server explorer->
Select database folder (.mdb File)-> right click->Choose properties->Fetch connection
string
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:DOTNET(.NET)
APPLICATIONSWin_ConnectivityWin_Connectivitystudent.accdb"
Dim cmd As New OleDbCommand
cmd.Connection = con
cmd.CommandText = "select * from stu"
Dim dr As OleDbDataReader
Dim dt As New DataTable
'For connected arch, you need to open connection and close connection explicitly.
con.Open()
dr = cmd.ExecuteReader()
dt.Load(dr)
TextBox1.Text = dt.Rows(i)(0)
TextBox2.Text = dt.Rows(i)(1)
con.Close()
End Sub
Private Sub Btn_FirstRecord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
49. UNIT II
Page 49
Btn_FirstRecord.Click
Dim con As New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:DOTNET(.NET)
APPLICATIONSWin_ConnectivityWin_Connectivitystudent.accdb"
Dim cmd As New OleDbCommand
cmd.Connection = con
cmd.CommandText = "select * from stu"
Dim dr As OleDbDataReader
Dim dt As New DataTable
con.Open()
dr = cmd.ExecuteReader()
dt.Load(dr)
i = 0
TextBox1.Text = dt.Rows(i)(0)
TextBox2.Text = dt.Rows(i)(1)
con.Close()
End Sub
Private Sub Btn_PreviousRecord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Btn_PreviousRecord.Click
Dim con As New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:DOTNET(.NET)
APPLICATIONSWin_ConnectivityWin_Connectivitystudent.accdb"
Dim cmd As New OleDbCommand
cmd.Connection = con
cmd.CommandText = "select * from stu"
Dim dr As OleDbDataReader
Dim dt As New DataTable
con.Open()
dr = cmd.ExecuteReader()
dt.Load(dr)
i = i - 1
TextBox1.Text = dt.Rows(i)(0)
TextBox2.Text = dt.Rows(i)(1)
con.Close()
End Sub
Private Sub Btn_NextRecord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Btn_NextRecord.Click
Dim con As New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:DOTNET(.NET)
APPLICATIONSWin_ConnectivityWin_Connectivitystudent.accdb"
Dim cmd As New OleDbCommand
cmd.Connection = con
cmd.CommandText = "select * from stu"
Dim dr As OleDbDataReader
Dim dt As New DataTable
con.Open()
dr = cmd.ExecuteReader()
dt.Load(dr)
i = i + 1
TextBox1.Text = dt.Rows(i)(0)
TextBox2.Text = dt.Rows(i)(1)
con.Close()
End Sub
Private Sub Btn_LastRecord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Btn_LastRecord.Click
Dim con As New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:DOTNET(.NET)
APPLICATIONSWin_ConnectivityWin_Connectivitystudent.accdb"
Dim cmd As New OleDbCommand
cmd.Connection = con
50. UNIT II
Page 50
cmd.CommandText = "select * from stu"
Dim dr As OleDbDataReader
Dim dt As New DataTable
con.Open()
dr = cmd.ExecuteReader()
dt.Load(dr)
i = dt.Rows.Count - 1
TextBox1.Text = dt.Rows(i)(0)
TextBox2.Text = dt.Rows(i)(1)
con.Close()
End Sub
Private Sub BtnInsertNewRecord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
BtnInsertNewRecord.Click
Dim con As New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:DOTNET(.NET)
APPLICATIONSWin_ConnectivityWin_Connectivitystudent.accdb"
Dim cmd As New OleDbCommand
cmd.Connection = con
cmd.CommandText = "insert into stu values(" & TextBox1.Text & ",'" & TextBox2.Text & "')"
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Sub
Private Sub BtnDeleteRecord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
BtnDeleteRecord.Click
Dim con As New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:DOTNET(.NET)
APPLICATIONSWin_ConnectivityWin_Connectivitystudent.accdb"
Dim cmd As New OleDbCommand
cmd.Connection = con
cmd.CommandText = "delete from stu where ID=" & TextBox1.Text
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Sub
End Class
1. Start Page
-> This is a first window which gets opened when we start Visual Studio.
51. UNIT II
Page 51
->We can use start Page to create a new project by clicking the project link in create or we can select existing
project from resent projects.
2. Toolbox
52. UNIT II
Page 52
-> The Toolbox Window contains a set of controls that can be placed on a Form wind
produce a graphical user interface.
-> The toolbox can be opened by choosing the command Toolbox in the
View menu.
-> The simplest method of adding a control to a form is to double-click the
desired object in the Toolbox. A control can also be added to a form by
selecting it and then dropping it onto the form.
-> It includes tabs like All Window forms, Common Controls, Containers,
Menus & Toolbars, Data, Components, Printing, Dialogs, Crystal Reports and
General. They appear when we are working with a window form in a designer
mode but when we switch to code designer then we see only general in toolbox.
->We can also add own tabs by right clicking the toolbox and selecting the add
tab item.
2. Solution Explorer Window
-> Solution Explorer Window provides an easy access to different application
files including files contains forms and codes.
-> It provides a tree view of all applications which are present in a solution.
A solution may contain different types of applications like Window
application, Web application, Console application, Class Library Etc.
3. Properties Window
53. UNIT II
Page 53
->Once a control i.e. object have been added to the form, we can set properties of objects through the help of
Properties window.
-> We can also access all events associated with an object through the help of Properties window.
->Two important properties of objects are the Name property and the Text property. The Name property
allows the programmer to assign a descriptive name to an object, rather than using the default name provided by
Visual Basic for that object. The value of the Text property of an object is displayed to the user when the
application is running.
4. Output Window
54. UNIT II
Page 54
-> The Output pane provides us the detail status of building and running programs.
-> We can see the output of a program with the help of System.console.write method.
55. UNIT II
Page 55
5. Component Tray
-> This includes those components which when are added to a form are visible at design time but not at runtime
for e.g. timer control.
56. UNIT II
Page 56
6. Server Explorer
-> Server explorer is a great tool which provides us a graphical environment to create database connection easily.
57. UNIT II
Page 57
7. Error List
-> Error List Window shows the error and warnings in current project. For example if we are trying to use a
variable which is not declared then it will show error.
58. UNIT II
Page 58
8. Object Browser and Class View Window
-> Class View presents solution and project in terms of classes they contain and the members of these classes. It
gives us an easy way of jumping to a member of class that we want to access quickly by just double clicking.
Object Browser Window lets us look at all the members of an object at once.
9. Debug and Release Versions.
->In debug version of a program VB stores a great amount of data needed to interface with the debugger in a
program when it runs.
->In release version a program does not have all the added data and it can run as stand alone program.
10. Break point
->We can insert break points into the program which are useful in tracking the program in step by step executable
manner when they are hit with the help of implementing the event.
59. UNIT II
Page 59
SIMILARITES BETWEEN VB AND VB.NET
Both languages support the creation of windows form application with the help of Graphical User Interface.
Both languages support event driven programming.
DIFFERENCEBETWEEN VB AND VB.NET
VB VB.NET
1. Integer Data type has changed.
Short (Int16), Integer (Int32), Long (Int64).
e.g.;
Dim Age As Integer
Dim ID As Long
Dim Age As Short
Dim ID As Integer
2. Defining user defined types (UDT) has a new syntax.
Type Customer
CustomerNumber as Long
CustomerName As String
End Type
Structure Customer
Public CustomerNumber as Integer
Public CustomerName As String
End Structure
3. Public Property Get CustomerName() As String
CustomerName = m_CustName
End Property
Public Property Let CustomerName(sCustName As String)
m_CustName = sCustName
End Property
3. Public Property CustomerName() As String
Get
CustomerName = m_CustName
End Get
Set
m_CustName = Value
End Set
End Property
4. Option Base can start from 1 or 0. 4. All arrays have Base 0.
5. It supports Unstructured exception handling. 5. It supports Structured as well as Unstructured
exception handling.
6. VB is object based. It doesn't support Inheritance and
polymorphism. It supports interfaces in an awkward way.
6. VB.Net is object oriented. It supports Inheritance
and polymorphism. It fully supports interface-based
programming.
7. VB doesn’t supports multithreading. 7. VB.Net supports multithreading.
8. By default the variable is variant. 8. By default the variable is object.
9. VB is interpreted language. 9. VB.Net is compiled language
10. It does not support concept of Partial classes. 10. It supports concept of Partial classes.
60. UNIT II
Page 60
11. 'If Not X Is Y' 11. It supports IsNot operator. ‘If X IsNot Y'
12. VB is an Unmanaged Language. It is not supported by
the feature of CLR.
12. VB.Net is a Managed Language. It has a support
of CLR feature.
13. VB has the drawback of DLL hell. 13. It do not have DLL hell drawback.
14. Dim x, y as Integer.
VB will consider x as Variant and y as Integer.
14. Dim x, y as Integer.
VB.Net will declare x and y both as Integer
15. ByRef is default. 15. ByVal is the default.
16. It does not support feature of Garbage Collection. 16. It supports feature of Garbage Collection.
17. It supports recordset and ADO for database
connectivity.
17. It supports ADO.NET for database connectivity.
18. It does not support interoperability. 18. It supports interoperability.