bca 303 unit 2 notes

61
UNIT-II VISUAL BASIC.NET

Upload: vinay-garg

Post on 30-Oct-2014

34 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: BCA 303 Unit 2 Notes

UNIT-IIVISUAL BASIC.NET

Page 2: BCA 303 Unit 2 Notes

Lecture-9

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.

DIFFERENCE BETWEEN VB AND VB.NET

VB VB.NET1. Integer Data type has changed. Short (Int16), Integer (Int32), Long (Int64).e.g.; Dim Age As IntegerDim ID As Long

Dim Age As ShortDim 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 StringEnd Structure

3. Public Property Get CustomerName() As StringCustomerName = 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 SetEnd 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 language10. It does not support concept of Partial classes. 10. It supports concept of Partial classes.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.

Page 3: BCA 303 Unit 2 Notes

Lecture-10

2.1 DECLARATION AND INITIALIZATION OF VARIABLES

The Dim statement is used for 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 specified in the first As clause encountered after its variablename part.

Dim A As IntegerPublic 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 assigned the Object data type but it can

cause slow execution.

2.1.2 Initialization

Dim A As Integer = 1Dim A As Integer = 1, B As Double = 2Dim 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.1.3 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 assigned a 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 need to redefine the value, the Const statement is the only place we need to make a change.

Dim Const DaysInYear = 365Private Const Days = 7Public Const Funday As String = "Sunday"

2.1.4 How to declare multiple constants in a single line

Public Const Four As Integer = 4, Five As Integer = 5, Six As Integer = 44

Page 4: BCA 303 Unit 2 Notes

2.2 DATA TYPES

The data type of a programming element refers to what kind of 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 +/-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

Page 5: BCA 303 Unit 2 Notes

†) (unsigned)

User-Defined (structure)

(inherits from ValueType)

Depends on implementing platform

Each member of the structure has a range determined by 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 derived from it. It also means that any other data type can be converted to Object.

2.2.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

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.2.2 Byte Data Type

1. Holds unsigned 8-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 unsigned type 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.2.3 Char Data Type

Page 6: BCA 303 Unit 2 Notes

1. Holds unsigned 2-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 and do not need the overhead of 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 and technical symbols.

Note:

Char is an unsigned type 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.

2.2.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 intend it 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

specified by the run-time locale, and it renders the time according to the time format (either 12-hour or 24-hour) specified by 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).Syntax: Dim DateAndTime As Date = #8/13/2002 12:14 PM#

Page 7: BCA 303 Unit 2 Notes

2.2.5 Double Data Type

1. Holds signed 8-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.2.6 Decimal Data Type

1. Holds signed 16-byte values representing 96-bit (12-byte) integer numbers scaled by 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.

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.2.7 Integer Data Type

1. Holds signed 32-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.

Page 8: BCA 303 Unit 2 Notes

2.2.8 Long Data Type

1. Holds signed 64-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.2.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.

2.2.10 SByte Data Type

1. Holds signed 8-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.

Page 9: BCA 303 Unit 2 Notes

2.2.11 Short Data Type

1. Holds signed 16-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.2.12 Single Data Type

1. Holds signed 4-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.2.13 String Data Type

1. Holds sequences of unsigned 2-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 overhead of Char(), an array of Char elements.

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.

Page 10: BCA 303 Unit 2 Notes

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 enclosed in quotation marks (" ") as String.

8. The corresponding type in the .NET Framework is the System.String class.

2.2.14 UInteger Data Type

1. Holds unsigned 32-bit (4-byte) integers ranging in value from 0 through 4,294,967,295.The UInteger data type provides the largest unsigned value in the most efficient data width.

2. The default value of UInteger is 0.

2.2.15 ULong Data Type

1. Holds unsigned 64-bit (8-byte) integers. It can be used to contain binary data.

2. The default value of ULong is 0.

3. ULong is an unsigned type, 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.2.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.2.17 UShort Data Type

1. Holds unsigned 16-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 unsigned type; it cannot represent a negative number. LS Compliance.

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:

Page 11: BCA 303 Unit 2 Notes

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.3. 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.3.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.3.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 implemented by .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.4 Type Conversion

The process of changing a value from one data type to another is called Type Conversion. Conversions are either Widening or Narrowing depending on the data capacities of the types involved. It is also implicit or explicit depending on the syntax in the source code.

2.4.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.

Page 12: BCA 303 Unit 2 Notes

2.4.1.1 Widening Conversions

Widening conversion changes a value to a data type that can accommodate any possible values of the original data. It always succeed at run time and never incur data loss and always performed implicitly.

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

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

Page 13: BCA 303 Unit 2 Notes

conversions always succeed at 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.4.1.2 Narrowing Conversions

Narrowing conversion changes a value to a data type that might not be able to hold some of the possible values.

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 enumerated type (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 derived from it

Narrowing conversions do not always succeed at run time, and can fail or incur data loss. An error occurs if the destination data type cannot receive the value being converted. 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.

Ex- Dim num1 As Integer =35786 Dim num2 As Short num2=num1 ‘Narrowing conversion so compiler doesn’t allow to perform implicitly. Here overflow exception occurred.

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 converted value is too large for the target type

2.5 Implicit & Explicit Conversion

2.5.1 Implicit Conversion

An implicit conversion doesn’t require any special syntax in the source code. Widening Conversion is always implicit.

Ex- Dim num1 As Integer =35786 Dim num2 As double num2=num1

2.5.2 Explicit Conversion

Explicit conversion uses a type conversion keyword. These keyword act like a function which accept one parameter.

Following functions are used to convert a value to a specific data type:-

Page 14: BCA 303 Unit 2 Notes

Function name Return data type

CBool() Boolean Data Type

CByte() Byte Data Type

CChar() Char Data Type

CDate() Date Data Type

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.2.1 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 = 1000Dim NewNumber As Single = CType (Number, Single)

2.5.2.2 TryCast   Function

It is a type conversion function which is used for any kind of 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 instead of having to handle a possible exception.

Dim Number As Long = 1000Dim NewNumber As Object = CType (Number, Object)

Summary:- Keyword Data types Run-time failure

CType() Any data types Throws InvalidCastException

TryCast() Reference types Returns Nothing

Page 15: BCA 303 Unit 2 Notes

only

2.6 Boxing & Unboxing

Boxing is the process of converting a value type to the object type or to any reference type implemented by this value. When the CLR boxes a value type , it wraps the value inside a System.Object and store it on the managed heap.

Unboxing is the reverse of boxing wherein object type is converted into value type.

Note:- Boxing is performed implicitly and Unboxing is performed explicitly.

Ex- Dim num1 As Integer =432 Dim obj As Object obj=num1 ‘ Boxing Process

Ex- Dim num1 As Integer Dim obj As Object=432 num1=CInt(obj) ‘ Unboxing Process

Lecture-11

2.7 Basic Operators

Visual Basic comes with many built-in operators that allow us to manipulate data. An operator performs a function on one or more operands. For example, we add two variables with the "+" addition operator and store the result in a third variable with the "=" assignment operator like this: int x + int y = int z. The two variables (x ,y) are called operands. There are different types of operators in Visual Basic and they are described below in the order of their precedence.

Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations that involve calculation of numeric values. The table below summarizes them:

Operator Use+ Addition- Subtraction* Multiplication\ Division/ Integer DivisionMOD Modulus Arithmetic (Return remainder)^ Exponentiation

Concatenation Operators

Concatenation operators join multiple strings into a single string. There are two concatenation operators, + and & as summarized below:

Operator Use+ String Concatenation& String Concatenation

Page 16: BCA 303 Unit 2 Notes

Note:- When concatenating a string variable with a numeric value then don’t use + operator otherwise it will give an error.

Comparison Operators

A comparison operator compares operands and returns a logical value based on whether the comparison is true or not. The table below summarizes them:

Operator Use= Equality<> Inequality (i.e Not Equal)< Less than> Greater than>= Greater than or equal to<= Less than or equal toLike Matches a string to pattern & return true if string matches

otherwise falseIs Compare 2 object reference variable and return true if

both refer to same object otherwise false.

Like Operator

Like operator matches a string to pattern and return true if string matches a pattern otherwise return false.

Syntax:Result= String Like Pattern

Note- Result will be of Boolean Type.

Ex- Dim Result as BooleanResult=”Hello” Like “He*”MsgBox(Result) ‘Return True

Pattern matching feature allow to match string using Wildcard Characters, Character-list or character ranges, in any combinations.

Character In pattern Matches in String? Any single character* Zero or more character# Any single digit (0-9)[charlist] Any single character in list

[!charlist]Any single character not in list i.e. match is made if any character except the characters in charlist is found in string

Example:-1. MsgBox (“Bat” Like “B?t”) O/P – True

MsgBox (“Bit” Like “B?t”) O/P – True

2. MsgBox(“John” Like “Jo*”) O/P- TrueMsgBox(“Joan” Like “Jo*”) O/P- TrueMsgBox(“Joann” Like “Jo*”) O/P- True

Page 17: BCA 303 Unit 2 Notes

3. MsgBox(“401” Like “#01”) O/P- TrueMsgBox(“part-301” Like “*3##”) O/P- True

4. MsgBox(“Bat” Like B[a-f]t) O/P - TrueMsgBox(“Bit” Like B[a-f]t) O/P - FalseMsgBox(“Bat” Like B[!a-f]t) O/P - True

Logical / Bitwise Operators

The logical operators compare Boolean expressions and return a Boolean result. In short, logical operators are expressions which return a true or false result over a conditional expression. The table below summarizes them:

Operator UseNot NegationAnd ConjunctionAndAlso ConjunctionOr DisjunctionOrElse DisjunctionXor Disjunction

Assignment Operator

Visual Basic .NET provides several assignment operators for abbreviating assignment statements.

Operator Use= Assignment+= Addition Assignment-+ Subtraction Assignment*= Multiplication Assignment/= Division Assignment\= Integer Division AssignmentMOD= Mod Assignment^= Exponentiation Assignment&= Concatenation Assignment

2.8 Enumeration

Enumeration is a distinct type consisting of a set of named constant called the Enumeration list. Enumerations provide a convenient way to work with sets of related constants 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 related values use the same enumeration name. For example, we can declare an enumeration for a set of integer constants associated with the days of the week, and then use the names of the days rather than their integer values in your code.

Every enumeration has an underlying type which can be any integral type. Integral data types are those that represent only whole number. Ex-Byte(unsigned),Short,integer,Long,SByte,Ushort,UInteger,ULong.

Note:- If we don’t specify data type for the enumerator then the default data type is imposed on enumeration which of Integer type.

Syntax for Declaring Enumeration:-

Page 18: BCA 303 Unit 2 Notes

Enum [Enumeration Name] [As] [Integral Data Type]

Enumeration list

End Enum

Example:-

Enum daysSundayMondayTuesdayWednesdayThursdayFridaySaturday

End Enum

Use of Enumeration

Console.WriteLine(Days. Sunday)

Note: 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 need to follow a sequential ordering. For example:-

Enum BoilingPoints As ByteFahrenheit = 212Celcius = 100

End EnumConsole.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 = 1End Enum

2.9 Option Statements

2.9.1 OPTION EXPLICIT

Forces explicit declaration of all variables to be used in the program if it is turned on.

Syntax:- Option Explicit [On|Off]

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.

Page 19: BCA 303 Unit 2 Notes

2.9.2 OPTION STRICT

Using Option Strict On we can prevent narrowing conversion which lead to data loss and causes runtime failure.. Option Strict ensures compile-time notification if narrowing conversions occurs without an explicit cast operator so that they can be avoided. It restricts implicit data type conversions to only widening conversions.

Syntax:- Option Strict [On|Off]

If used, the Option Strict statement must appear before any other source code. Because Option Strict On provides strong typing, prevents unintended type 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.9.3 OPTION COMPARE

This is used to specify the default comparison method to be used when need to 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.

Syntax:- Option Compare [Text|Binary]

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.

Page 20: BCA 303 Unit 2 Notes

2.9.4. OPTION INFER

Syntax:- Option Infer [On|Off]

When Option Infer is set to “On” then we can declare variables without explicitly stating a data type. Compiler will infer the data type of a variable from the type of value it store.

2.10 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.ConsoleModule 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.11 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:-2.11.1 BLOCK SCOPEA block is a set of statements enclosed within initiating and terminating 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.11.2 PROCEDURE SCOPE

An element declared within 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()

Page 21: BCA 303 Unit 2 Notes

Dim a As Integer Writleine(a) End Sub

2.11.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.11.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 referred to by code anywhere in the namespace of its declaration.

Namespace scope includes nested namespaces. An element available from within a namespace is also available from within any namespace nested inside 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

2.12 CHECKING DATA TYPES FUNCTIONS

Function DescriptionIsArray() An array of values, rather than a single valueIsDate() A Date Data Type (Visual Basic) value, or a string that can be interpreted as a date

and time valueIsDBNull() An object of type DBNull, which represents missing or nonexistent dataIsError () An exception object, which derives from ExceptionIsNothing() Nothing (Visual Basic), that is, no object is currently assigned to the variableIsNumeric() A number, or a string that can be interpreted as a numberIsReference() A reference type (such as a string, array, delegate, or class type)

Page 22: BCA 303 Unit 2 Notes

Lecture-12

2.13 CONTROL FLOW

CONTROL FLOW IN VISUAL BASIC

Control structures allow regulating the flow of program's execution.

Decision Structures

(A)If…Then…Else

If condition Then 'statements End If

Dim A >=10

Control Flow

Decision Structures Loop Structures

Page 23: BCA 303 Unit 2 Notes

If A > 10 Then A = A + 1 : B = B + A : C = C + B

Variation

If condition Then'statements Else 'statementsEnd If

If condition1 Then 'statementsElseIf condition2 Then 'statementsElseIf condition3 Then 'statementsElse 'statements End If

Example

Dim score As Integer, Result As Stringscore = InputBox("Enter score")If score < 50 Then Result = "Failed"ElseIf score < 75 Then Result = "Pass"ElseIf score < 90 Then Result = "Very Good"Else Result = "Excellent"End IfMsgBox(Result)

(B) Select...Case StatementAn alternative to the efficient, but difficult-to-read, code of the multiple-ElseIf structure is the Select Case structure, which compares one expression to different values. The advantage of the Select Case statement over multiple If…Then…Else/ElseIf statements is that it makes the code easier to read and maintain.

Select Case expressionCase value1 statementblock1Case value2 statementblock2Case Else statementblockNEnd Select

ExampleDim message As StringSelect Case Now.DayOfWeekCase DayOfWeek.Mondaymessage = "Have a nice week"

Page 24: BCA 303 Unit 2 Notes

Case DayOfWeek.Fridaymessage = "Have a nice weekend"Case Else message = "Welcome back!"End SelectMsgBox(message)Select Case Now.DayOfWeekCase DayOfWeek.Monday message = "Have a nice week"Case DayOfWeek.Tuesday, DayOfWeek.Wednesday, _ DayOfWeek.Thursday, DayOfWeek.Friday message = "Welcome back!"Case DayOfWeek.Friday, DayOfWeek.Saturday, DayOfWeek.Sunday message = "Have a nice weekend!"End SelectMsgBox(message)

Looping Structures

(A)FOR…NEXT

For counter = start To end [Step increment] statementsNext [counter]

Example:For i = 0 To 10 Console.WriteLine(i) i = i + 1Next i

(B)Do…LoopTo execute a block of statements while a condition is true.

Do While condition Statement(s)Loop

Example Dim d, e As Integer d = 0 e = 6 While e > 4 e -= 1 d += 1 End While System.Console.WriteLine("The Loop ran " & e & "times")To execute a block of statements until the condition becomes true.

(C)Do Until….Loop

Page 25: BCA 303 Unit 2 Notes

Do Until Condition Statement(s)Loop

Example Dim str As String Do Until str = "Cool" Console.WriteLine("What to do?") str = System.Console.ReadLine() Loop

2.14 CONTINUE STATEMENT

This statement transfers control immediately to the next iteration of a loop. You can transfer from inside a Do, For, or While loop to the next iteration of that loop. Control passes immediately to the loop condition test, which is equivalent to transferring to the For or While statement, or to the Do or Loop statement that contains the Until or While clause.

Module Module1 Sub Main() Dim index As Integer = -1 Dim input As Integer = 0 Dim unemp As Integer = -1 Do index += 1Console.WriteLine("1. Enter 1 for Employed" & vbNewLine & "2. Enter 0 for Exit" & vbNewLine & "3. Enter 2 for UnEmployed") input = Val(Console.ReadLine()) If input = 1 Then Continue Do

Page 26: BCA 303 Unit 2 Notes

unemp += 1 Loop While input <> 0

Console.WriteLine("{0} Out of {1} people are UnEmployed", unemp, index)

Console.ReadLine() End SubEnd Module

2.15 WITH ... END WITH

It executes a series of statements making repeated reference to a single object or structure.

We can use a With...End With structure to specify the object once for all of the statements.

With testObject

Page 27: BCA 303 Unit 2 Notes

.Height = 100 .Text = "Hello, World"

.ForeColor = System.Drawing.Color.Green End With

HOW TO: ADD A COMMENT Comment character (') at the beginning or in the middle of any line ' This entire line is a comment.

Dim Total As Decimal = 0 ' Sales total for today

HOW TO: BREAK AND COMBINE STATEMENTS IN CODE

cmd.CommandText = _ "SELECT * FROM Titles JOIN Publishers " _ & "ON Publishers.PubId = Titles.PubID " _ & "WHERE Publishers.State = 'CA'"

SPECIAL CHARACTERS IN CODE

1. PARENTHESES2. SEPARATORS

MEMBER ACCESS OPERATORSDOT (.) OPERATOR

Dim nextForm As New ' Access Text member (property) of Form class (on nextForm object). nextForm.Text = "This is the next form" ' Access Close member (method) on nextForm nextForm.Close()

Page 28: BCA 303 Unit 2 Notes

Lecture-13

2.16 Arrays

An array is a set of values that are logically related to each other, such as the number of students in each grade in a grammar school.An array allows you to refer to these related values by the same name and to use a number, called an index or subscript, to tell them apart. The individual values are called the 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 IntegerDim 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 contained in 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.16.1 Array Dimensions

Page 29: BCA 303 Unit 2 Notes

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 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 DimensionMany 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.

Page 30: BCA 303 Unit 2 Notes

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 DimensionsSome 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 and place 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 DimensionsA 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 DimensionsAlthough an array can have as many as 32 dimensions, it 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 DoubleNow 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.

2.16.2 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 instead of a multidimensional array.

Page 31: BCA 303 Unit 2 Notes

Dim colors(2)() As String‘Declaring an array of 3 arrayscolors(0)=New String{“Red”,”Blue”,”Green”}‘Initializing the first array to 3 members and setting valuescolors(1)=New String(){“yellow”,”purple”,”green”,”violet”}‘Initializing the second array to 4 members and setting valuesColors(2)=New string(){“red”,”black”,”white”,”grey”,”aqua”}‘Initializing the third array to 5 members and setting values

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 dimensions to be -1, as shown in the following example.

Dim twoDimensionalStrings(-1, 3) As String

You might need to create a zero-length array under the following circumstances: 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 keep the 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.16.3 DYNAMIC ARRAY

We can change the size of an array after creating them

Dim Test(10) As IntegerReDim Test(25) ‘Reinitializing the array

When using the ReDim statement all the data contained in the array is lost. If you want to preserve existing data when reinitializing an array then you should use the Preserve.

Dim Test() As integer={1,3,5}ReDim Preserve Test(25)‘resizes the arrayn and return the data in elements 0 to 2.

Page 32: BCA 303 Unit 2 Notes

Lecture-14

2.17.1 Array Class: Method and Properties

All Array derived from the System.Array namespace so we must import this namespace to use the method and properties.

Properties:

1.LengthReturn the length(total number of element) of a one-dimensional array in integer.

Syntax: Arrayname.Length

2.2.RankReturn number of dimension of array.

Syntax: Arrayname.Length

Methods

1. Clear()Sets a range of elements to 0,NULL,False depending on the element type in one dimensional array.

Syntax: Array.Clear(ArrayName, Starting index value, number of element to clear)

2.GetLength()Return the total n umber of element in the specified dimension of the array.

3.GetLowerBound()

4.GetUpperBound()

5.GetValue()

6.SetValue()

7.Sort()

7.Reverse()

Page 33: BCA 303 Unit 2 Notes

2.17.2 String Class : Method and Properties

String class under the System.String namespace provide several built in methods to facilitate comparison and manipulation of string.

Methods

1.Compare()2.Concat()

3.ToLower()

4.ToUpper()

5.Trim()

6.TrimEnd()

7.TrimStart()

8.SubString()

9.Replace()

10.Remove()

11.Insert()

Lecture-15

2.18 EXCEPTION HANDLING

Errors Exceptions

Exception is an abnormal/unexpected/exceptional condition that encounter during runtime.Error can exceptional/unexpected or not. Error is a known workflow within application. For Example- Username not provided during authentication is an error.Exception can be used to convey an error but more generally is used to convey that something unexpected occurred.So, all Exceptions are Error but not vice-versa.

TYPES OF EXCEPTION HANDLING

Unstructured Exception Handling Structured Exception Handling

2.18.1 UNSTRUCTURED EXCEPTION HANDLING

Unstructured exceptional handling uses “On Error GoTo………” statement for handling the execution.

Page 34: BCA 303 Unit 2 Notes

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:

Module Module1 Sub Main()

On Error GoTo handler Dim a, b, c As Integer a = 1 b = 0 c = a / b Exit Subhandler: System.Console.WriteLine("Error")

System.Console.ReadLine() End SubEnd Module

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

Page 35: BCA 303 Unit 2 Notes

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()

Example:

On Error GoTo handler Dim a, b, c As Integer a = 1 b = 0 c = a / bhandler:

If TypeOf Err.GetException() Is OverflowException Then System.Console.WriteLine("overflow error") End If

System.Console.ReadLine()

Page 36: BCA 303 Unit 2 Notes

Exit Sub

Example:

Sub Main() On Error GoTo -1 Dim a, b, c As Integer a = 1 b = 0 c = a / bhandler:

If TypeOf Err.GetException() Is OverflowException Then System.Console.WriteLine("overflow error") End If

System.Console.ReadLine() Exit Sub

Example:

On Error GoTo handler Dim a, b, c As Integer a = 1

Page 37: BCA 303 Unit 2 Notes

b = 0 Err.Raise(6)

handler:

System.Console.WriteLine(Err.Description) System.Console.ReadLine()Exit Sub

2.18.2 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

Page 38: BCA 303 Unit 2 Notes

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) 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

Page 39: BCA 303 Unit 2 Notes
Page 40: BCA 303 Unit 2 Notes

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

WriteOnly Property FileName() As String

Page 41: BCA 303 Unit 2 Notes

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 MethodsNo return type May have return typeSame 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 Public name As String Sub display(ByVal id As Integer)

Console.WriteLine(id)

Page 42: BCA 303 Unit 2 Notes

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 CLASSESValue type. Structures use stack allocation Reference type. Classes use heap

allocation.

Cannot have default constructors. Can have default constructorsCannot 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.

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.

Page 43: BCA 303 Unit 2 Notes

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()

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

Page 44: BCA 303 Unit 2 Notes

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#)

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

Page 45: BCA 303 Unit 2 Notes

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 SubEnd Class

Class Programmer Inherits Human Public Sub StealCode() Console.Writeline("Stealing code") End SubEnd 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.

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()

Page 46: BCA 303 Unit 2 Notes

Console.Writeline("Speaking Hindi") End SubEnd 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

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

Page 47: BCA 303 Unit 2 Notes

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