[go: up one dir, main page]

0% found this document useful (0 votes)
21 views33 pages

Unit 3

The document discusses VB.NET language fundamentals including classes, objects, methods, fields, properties, inheritance, polymorphism, operator overloading, interfaces, arrays, indexers, collections, strings, regular expressions, constants, and enumerations.

Uploaded by

rajeshcse2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views33 pages

Unit 3

The document discusses VB.NET language fundamentals including classes, objects, methods, fields, properties, inheritance, polymorphism, operator overloading, interfaces, arrays, indexers, collections, strings, regular expressions, constants, and enumerations.

Uploaded by

rajeshcse2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 33

PLATFORM TECHNOLOGY

UNIT – III
VB .NET: Language Fundamentals – Classes and Objects – Methods – Fields and Properties
- Inheritance and Polymorphism – Operator Overloading – Interfaces – Arrays – Indexers
and Collections – Strings and Regular Expressions.

VB .NET: Language Fundamentals


VB.Net is an object-oriented programming language. In Object-Oriented Programming methodology,
a program consists of various objects that interact with each other by means of actions. The actions
that an object may take are called methods. Objects of the same kind are said to have the same type
or, more often, are said to be in the same class.
When we consider a VB.Net program, it can be defined as a collection of objects that communicate
via invoking each other's methods. Let us now briefly look into what do class, object, methods and
instance variables mean.
 Object − Objects have states and behaviors. Example: A dog has states - color, name, breed
as well as behaviors - wagging, barking, eating, etc. An object is an instance of a class.
 Class − A class can be defined as a template/blueprint that describes the behaviors/states that
objects of its type support.
 Methods − A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are executed.
 Instance Variables − Each object has its unique set of instance variables. An object's state is
created by the values assigned to these instance variables.

Identifiers
An identifier is a name used to identify a class, variable, function, or any other user-defined item.
The basic rules for naming classes in VB.Net are as follows −
 A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9)
or underscore. The first character in an identifier cannot be a digit.
 It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; : " ' /
and \. However, an underscore ( _ ) can be used.
 It should not be a reserved keyword.

Data Types Available in VB.Net


Data types refer to an extensive system used for declaring variables or functions of different types.
The type of a variable determines how much space it occupies in storage and how the bit pattern
stored is interpreted.
VB.Net provides a wide range of data types. The following table shows all the data types available –

PLATFORM TECHNOLOGY CS T73 Page 1


Data Type Storage Allocation Value Range

Boolean Depends on implementing True or False


platform

Byte 1 byte 0 through 255 (unsigned)

Char 2 bytes 0 through 65535 (unsigned)

Date 8 bytes 0:00:00 (midnight) on January 1, 0001 through 11:59:59 PM


on December 31, 9999

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

Double 8 bytes
-1.79769313486231570E+308 through -
4.94065645841246544E-324, for negative values
4.94065645841246544E-324 through
1.79769313486231570E+308, for positive values

Integer 4 bytes -2,147,483,648 through 2,147,483,647 (signed)

Long 8 bytes -9,223,372,036,854,775,808 through


9,223,372,036,854,775,807(signed)

Object Any type can be stored in a variable of type Object


4 bytes on 32-bit
platform
8 bytes on 64-bit
platform

SByte 1 byte -128 through 127 (signed)

Short 2 bytes -32,768 through 32,767 (signed)

Single 4 bytes
-3.4028235E+38 through -1.401298E-45 for negative
values;
1.401298E-45 through 3.4028235E+38 for positive
values

String Depends on implementing 0 to approximately 2 billion Unicode characters


platform

UInteger 4 bytes 0 through 4,294,967,295 (unsigned)

ULong 8 bytes 0 through 18,446,744,073,709,551,615 (unsigned)

PLATFORM TECHNOLOGY CS T73 Page 2


User-Defined Depends on implementing Each member of the structure has a range determined by its
platform data type and independent of the ranges of the other members

UShort 2 bytes 0 through 65,535 (unsigned)

VB.Net – Variables
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable
in VB.Net has a specific type, which determines the size and layout of the variable's memory; the range of
values that can be stored within that memory; and the set of operations that can be applied to the variable.

We have already discussed various data types. The basic value types provided in VB.Net can be
categorized as −

Type Example

Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong and Char

Floating point types Single and Double

Decimal types Decimal

Boolean types True or False values, as assigned

Date types Date

VB.Net also allows defining other value types of variable like Enum and reference types of variables
like Class. We will discuss date types and Classes in subsequent chapters.

Variable Declaration in VB.Net


The Dim statement is used for variable declaration and storage allocation for one or more variables. The
Dim statement is used at module, class, structure, procedure or block level.

Syntax for variable declaration in VB.Net is −

[ < attributelist > ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]]

[ ReadOnly ] Dim [ WithEvents ] variablelist

Where,

 attributelist is a list of attributes that apply to the variable. Optional.

 accessmodifier defines the access levels of the variables, it has values as - Public, Protected,
Friend, Protected Friend and Private. Optional.

PLATFORM TECHNOLOGY CS T73 Page 3


 Shared declares a shared variable, which is not associated with any specific instance of a class or
structure, rather available to all the instances of the class or structure. Optional.

 Shadows indicate that the variable re-declares and hides an identically named element, or set of
overloaded elements, in a base class. Optional.

 Static indicates that the variable will retain its value, even when the after termination of the
procedure in which it is declared. Optional.

 ReadOnly means the variable can be read, but not written. Optional.

 WithEvents specifies that the variable is used to respond to events raised by the instance assigned
to the variable. Optional.

 Variablelist provides the list of variables declared.

Each variable in the variable list has the following syntax and parts –

variablename[ ( [ boundslist ] ) ] [ As [ New ] datatype ] [ = initializer ]

Where,

 variablename − is the name of the variable

 boundslist − optional. It provides list of bounds of each dimension of an array variable.

 New − optional. It creates a new instance of the class when the Dim statement runs.

 datatype − Required if Option Strict is On. It specifies the data type of the variable.

 initializer − Optional if New is not specified. Expression that is evaluated and assigned to the
variable when it is created.

VB.Net - Constants and Enumerations


Declaring Constants
In VB.Net, constants are declared using the Const statement. The Const statement is used at module,
class, structure, procedure, or block level for use in place of literal values.
The syntax for the Const statement is −
[ < attributelist > ] [ accessmodifier ] [ Shadows ]
Const constantlist
Where,
 attributelist − specifies the list of attributes applied to the constants; you can provide multiple
attributes separated by commas. Optional.
 accessmodifier − specifies which code can access these constants. Optional. Values can be
either of the: Public, Protected, Friend, Protected Friend, or Private.

PLATFORM TECHNOLOGY CS T73 Page 4


 Shadows − this makes the constant hide a programming element of identical name in a base
class. Optional.
 Constantlist − gives the list of names of constants declared. Required.
Where, each constant name has the following syntax and parts −
constantname [ As datatype ] = initializer
 constantname − specifies the name of the constant
 datatype − specifies the data type of the constant
 initializer − specifies the value assigned to the constant
For example,
'The following statements declare constants.'
Const maxval As Long = 4999
Public Const message As String = "HELLO"
Private Const piValue As Double = 3.1415

CLASSES AND OBJECTS IN VB .NET

 A class is used to specify the form of an object and it combines data representation and
methods for manipulating that data into one neat package.

 The data and functions within a class are called members of the class.

 When you define a class, you define a blueprint for a data type.

 This doesn't actually define any data, but it does define what the class name means, that
is, what an object of the class will consist of and what operations can be performed on
such an object.

 The keyword public determines the access attributes of the members of the class that
follow it. A public member can be accessed from outside the class anywhere within the
scope of the class object. You can also specify the members of a class
as private or protected which we will discuss in a sub-section.
Objects:

 A class provides the blueprints for objects, so basically an object is created from a class.

Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 OBJECT of type Box
Dim Box2 As Box = New Box() ' Declare Box2 OBJECT of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here
' box 1 specification
Box1.height = 5.0

PLATFORM TECHNOLOGY CS T73 Page 5


Box1.length = 6.0
Box1.breadth = 7.0
' box 2 specification
Box2.height = 10.0
Box2.length = 12.0
Box2.breadth = 13.0
'volume of box 1
volume = Box1.height * Box1.length * Box1.breadth
Console.WriteLine("Volume of Box1 : {0}", volume)
'volume of box 2
volume = Box2.height * Box2.length * Box2.breadth
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:

Volume of Box1 : 210


Volume of Box2 : 1560

FIELDS

 Fields, also known as data members, hold the internal state of an object.

 Their declarations appear only within class and structure declarations.

 Field declarations include an access modifier, which determines how visible the field is
from code outside the containing class definition.

 The value stored in a field is specific to a particular object instance.

 Two instances can have different values in their corresponding fields. For example:

 Dim emp1 As New Employee( )

 Dim emp2 As New Employee( )

 emp1.EmployeeNumber = 10

 emp2.EmployeeNumber = 20 ' Doesn't affect emp1.

 Sometimes it is desirable to share a single value among all instances of a particular class.
Declaring a field using the Shared keyword does this, as shown here:

 Public Class X

PLATFORM TECHNOLOGY CS T73 Page 6


 Public Shared a As Integer

 End Class

 Changing the field value through one instance affects what all other instances see. For
example:

 Dim q As New X( )

 Dim r As New X( )

 q.a = 10

 r.a = 20

 Console.WriteLine(q.a) ' Writes 20, not 10.

 Shared fields are also accessible through the class name:

 Console.WriteLine(X.a)

READ-ONLY FIELDS

 Fields can be declared with the ReadOnly modifier, which signifies that the field's value
can be set only in a constructor for the enclosing class.

 This gives the benefits of a constant when the value of the constant isn't known at
compile time or can't be expressed in a constant initializer.

 Here's an example of a class that has a read-only field initialized in the class's
constructor:

 Public Class MyDataTier

 Public ReadOnly ActiveConnection As System.Data.SqlClient.SqlConnection

 Public Sub New(ByVal ConnectionString As String)

 ActiveConnection = NeW
System.Data.SqlClient.SqlConnection(ConnectionString)

 End Sub

 End Class

 The ReadOnly modifier applies only to the field itself—not to members of any object
referenced by the field. For example, given the previous declaration of the MyDataTier
class, the following code is legal:

PLATFORM TECHNOLOGY CS T73 Page 7


 Dim mydata As New MyDataTier(strConnection)

 mydata.ActiveConnection.ConnectionString = strSomeOtherConnection

METHODS

Methods are members that contain code. They are either subroutines (which don't have a return
value) or functions (which do have a return value).

Subroutine definitions look like this:

[ method_modifiers ] Sub [ attribute_list ] method_name ( [ parameter_list ] ) [handles_or_implements ]

[ method_body ]

End Sub

Function definitions look like this:


[ method_modifiers ] Function method_name ( [ parameter_list ] ) [ As type_name ] [handles_or_implements ]

[ method_body ]

End Function

EXAMPLE:

Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
Public Sub setLength(ByVal len As Double)
length = len
End Sub
Public Sub setBreadth(ByVal bre As Double)
breadth = bre
End Sub
Public Sub setHeight(ByVal hei As Double)
height = hei
End Sub
Public Function getVolume() As Double
Return length * breadth * height
End Function
End Class

PLATFORM TECHNOLOGY CS T73 Page 8


Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here

' box 1 specification


Box1.setLength(6.0)
Box1.setBreadth(7.0)
Box1.setHeight(5.0)

'box 2 specification
Box2.setLength(12.0)
Box2.setBreadth(13.0)
Box2.setHeight(10.0)

' volume of box 1


volume = Box1.getVolume()
Console.WriteLine("Volume of Box1 : {0}", volume)

'volume of box 2
volume = Box2.getVolume()
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:

Volume of Box1 : 210


Volume of Box2 : 1560

PROPERTY
 A Property is similar to a Function.With a getter and a setter, it controls access to a
value.
 This value is called a backing store.
 With Get it returns a value. With Set it stores a value.

GET, SET
 This example program uses the Property keyword.
 On the Number () property, we provide a Get block and a Set block.
 In Get we return a value the backing store count.

PLATFORM TECHNOLOGY CS T73 Page 9


 In Set we receive a parameter and then store it in the count field.

TYPES:
 A property can have any data type.
 It does not need to be an Integer.
 It can be a Class.

Program that uses property syntax: VB.NET


Class Example
Private _count As Integer
Public Property Number() As Integer
Get
Return _count
End Get
Set(ByVal value As Integer)
_count = value
End Set
End Property
End Class

Module Module1
Sub Main()
Dim e As Example = New Example()
' Set property.
e.Number = 1
' Get property.
Console.WriteLine(e.Number)
End Sub
End Module

Output
1

 When the value 1 is assigned to the Number property, Set is executed.


 The count field stores the value 1.
 When the Number property is accessed but not assigned to, Get is executed.
 The value of the count field is returned.
 A property must have both Get and Set members. It is possible to use the ReadOnly or
WriteOnly keywords to eliminate this requirement.

PLATFORM TECHNOLOGY CS T73 Page 10


READONLY

 The ReadOnly modifier changes the Property type to only have a Get method.
 In this program, the Count() property returns a constant Integer.
 But Get could perform any calculation and return the value of a field.
 ReadOnly does not require a constant return value.
 If we try to assign a value to Count, we get this error: "Property Count is ReadOnly." So
don't do that.

Program that uses ReadOnly Property: VB.NET


Class Example
Public ReadOnly Property Count() As Integer
Get
Return 500
End Get
End Property
End Class

Module Module1
Sub Main()
Dim e As Example = New Example()
Console.WriteLine(e.Count)
End Sub
End Module

Output

500

INHERITANCE

 Visual Basic supports inheritance, which is the ability to define classes that serve as the
basis for derived classes.
 Derived classes inherit, and can extend, the properties, methods, and events of the base
class. Derived classes can also override inherited methods with new implementations.
 By default, all classes created with Visual Basic are inheritable.

PLATFORM TECHNOLOGY CS T73 Page 11


 Inheritance lets you write and debug a class one time and then reuse that code as the basis
of new classes.
 Inheritance also lets you use inheritance-based polymorphism, which is the ability to
define classes that can be used interchangeably by client code at run time, but with
functionally different, yet identically named methods or properties.
SYNTAX

The syntax used in VB.Net for creating derived classes is as follows:

<access-specifier> Class <base_class>


...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class

' Base class


Class Shape
Protected width As Integer
Protected height As Integer
Public Sub setWidth(ByVal w As Integer)
width = w
End Sub
Public Sub setHeight(ByVal h As Integer)
height = h
End Sub
End Class
' Derived class
Class Rectangle : Inherits Shape
Public Function getArea() As Integer
Return (width * height)
End Function
End Class
Class RectangleTester
Shared Sub Main()
Dim rect As Rectangle = New Rectangle()
rect.setWidth(5)
rect.setHeight(7)
' Print the area of the object.
Console.WriteLine("Total area: {0}", rect.getArea())
Console.ReadKey()
End Sub
End Class

PLATFORM TECHNOLOGY CS T73 Page 12


When the above code is compiled and executed, it produces the following result:

Total area: 35

POLYMORPHISM

 It is the ability of classes to provide different implementation of methods that are called
by same name.

 Polymorphism is one of the primary characteristics of Object Oriented Programming.

 “Poly” means “many” and “morph” means “form”.

 Thus polymorphism refers to being able to use many form of a type without regard to the
details.

 Polymorphism is the ability to redefine method for derived classes.


Types of Polymorphism

Compile Time Polymorphism.

Runtime Polymorphism.

Compile Time Polymorphism

 Compile time Polymorphism also known as Method Overloading.

 Method Overloading means having two or more methods with the same name but with
different parameters.

 It is also called as static polymorphism.

 Which method is to be called is decided at the compile time only.

 In static Polymorphism decision is taken at the Compile time.


Module Module1
Public Class mul
Public a, b As Integer
Public c, d As Double

Public Function mul(ByVal a As Integer) As Integer


Return a
End Function
Public Function mul(ByVal a As Integer,
ByVal b As Integer) As Integer
Return a * b
End Function
Public Function mul(ByVal d As Double,

PLATFORM TECHNOLOGY CS T73 Page 13


ByVal c As Double) As Double
Return d * c
End Function

End Class

Sub Main()
Dim res As New mul
System.Console.WriteLine
("Overloaded Values of Class Mul is::")
System.Console.WriteLine(res.mul(10))
System.Console.WriteLine(res.mul(20, 10))
System.Console.WriteLine(res.mul(12.12, 13.23))
Console.Read()
End Sub
End Module
Result:
Overloaded values of Class Mul is:
10
200
160.3476

Runtime Polymorphism

 Run Time Polymorphism also known as Method Overriding.

 Method Overriding means having two or more methods with the same name, same
parameters but with different implementation.

 It is also called as Dynamic Polymorphism.

 In this process, an overridden method is called through reference variable of a superclass;


the determination of the method to be called is based on the object being referred to by
reference variable.

 The parent class uses the same virtual keyword. Every class that overrides the virtual
method will use the override keyword.
Over riding in VB.NET

Overriding in VB.net is method by which a inherited property or a method is overidden to


perform a different functionality in a derived class. The base class function is declared using a
keyword Overridable and the derived class function where the functionality is changed contains
an keyword Overrides.

Example:
Module Module1

Class Over

PLATFORM TECHNOLOGY CS T73 Page 14


Public Overridable Function add(ByVal x As Integer,
ByVal y As Integer)
Console.WriteLine('Function Inside Base Class')
Return (x + y)
End Function
End Class

Class DerOver
Inherits Over
Public Overrides Function add(ByVal x As Integer,
ByVal y As Integer)
Console.WriteLine(MyBase.add(120, 100))
Console.WriteLine('Function Inside Derived Class')
Return (x + y)
End Function
End Class

Sub Main()
Dim obj As New DerOver
Console.WriteLine(obj.add(10, 100))
Console.Read()
End Sub
End Module
Result:
Function Inside Base Class
220
Function Inside Derived Class
110
Description:

In the above overriding example the base class function add is overridden in the derived class
using the MyBase.add(120,100)statement. So first the overidden value is displayed, then the
value from the derived class is displayed.

OPERATOR OVERLOADING

 Operator overloading is the ability for you to define procedures for a set of operators on a
given type.
 This allows you to write more intuitive and more readable code.
 When an operator can perform more than one operations, specially with objects, known
as operator overloading.

 A function name can be replaced with the operator using operator keyword.

Important points related to Operator overloading or guidelines:

PLATFORM TECHNOLOGY CS T73 Page 15


 Don't change an operator's semantic meaning. The result of an operator should be
intuitive.
 Make certain overloaded operators are shared methods.
 You cannot overload assignment e.g., the "=" operator .

The operators that can be defined on your class or structure are as follows:
 Unary operators:
 + - Not IsTrue IsFalse CType
 Binary operators:

 + - * / \ & Like Mod And Or Xor


 ^ << >> = <> > < >= <=
 You can't overload member access, method invocation, or the AndAlso, OrElse,
New, TypeOf... Is, Is, IsNot, AddressOf, GetType, and AsType operators.
 Note that assignment itself (=) is a statement, so you can't overload it either.
 Secondly, operator overloading cannot be used to change to order in which operators are
executed on a given line.
 For example, multiplication will always happen before addition, unless parentheses are
used appropriately.
Module Module1
Class Complex
Private x As [Double]
Private y As [Double]
Public Sub New()
End Sub
Public Sub New(ByVal real As [Double], ByVal image As [Double])
x = real
y = image
End Sub
Public Shared Operator +(ByVal c1 As complex, ByVal c2 As complex) As complex
Dim c3 As New Complex()
c3.x = c1.x + c2.x
c3.y = c1.y + c2.y
Return (c3)
End Operator
Public Sub Display()
Console.Write(x)
Console.Write("+j" & Convert.ToString(y))
Console.WriteLine()
End Sub
End Class
Sub Main()
Dim a As Complex, b As Complex, c As Complex
a = New Complex(2.5, 3.5)
b = New Complex(1.6, 2.7)
c=a+b

PLATFORM TECHNOLOGY CS T73 Page 16


Console.Write("a=")
a.Display()
Console.Write("b=")
b.Display()
Console.Write("c=")
c.Display()
End Sub
End Module

OUTPUT

a=2.5+3.5j

b=1.6+2.7j

c=4.1+6.2j

INTERFACES

 Interfaces in VB.net are used to define the class members using a keyword Interface,
without actually specifying how it should be implemented in a Class.
 Interfaces are examples for multiple Inheritances and are implemented in the classes
using the keyword Implements that is used before any Dim statement in a class.

Example:
Module Module1
Public Interface Interface1
Function Add(ByVal x As Integer) As Integer
End Interface

Public Class first Implements Interface1


Public Function Add(ByVal x As Integer) As Integer Implements Interface1.Add
Console.WriteLine("Implementing x+x in first class::" & (x + x))
End Function
End Class

Public Class second Implements Interface1


Public Function Add(ByVal x As Integer) As Integer Implements Interface1.Add
Console.WriteLine("Implementing x+x+x in second class::" & (x + x + x))
End Function
End Class

Sub Main()
Dim obj1 As New first
Dim obj2 As New second
obj1.Add(10)
obj2.Add(50)
Console.Read()

PLATFORM TECHNOLOGY CS T73 Page 17


End Sub
End Module
Result:
Implementing x+x in first class:: 20
Implementing x+x+x in second class:: 150
Description:

In the above example interface Interface1 is implemented in classes first and second but
differently to add the value of 'x' twice and thrice respectively.

ARRAY

 An array stores a fixed-size sequential collection of elements of the same type.

 An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.

 All arrays consist of contiguous memory locations.

 The lowest address corresponds to the first element and the highest address to the last
element.

CREATING ARRAYS IN VB.NET


To declare an array in VB.Net, you use the Dim statement. For example,

Dim intData(30) ' an array of 31 elements


Dim strData(20) As String ' an array of 21 strings
Dim twoDarray(10, 20) As Integer 'a two dimensional array of integers
Dim ranges(10, 100) 'a two dimensional array

You can also initialize the array elements while declaring the array. For example,

Dim intData() As Integer = {12, 16, 20, 24, 28, 32}


Dim names() As String = {"Karthik", "Sandhya", _
"Shivangi", "Ashwitha", "Somnath"}
Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}

The elements in an array can be stored and accessed by using the index of the array. The
following program demonstrates this:

PLATFORM TECHNOLOGY CS T73 Page 18


Module arrayApl
Sub Main()
Dim n(10) As Integer ' n is an array of 11 integers '
Dim i, j As Integer
' initialize elements of array n '
For i = 0 To 10
n(i) = i + 100 ' set element at location i to i + 100
Next i
' output each array element's value '
For j = 0 To 10
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:

Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110

MULTI-DIMENSIONAL ARRAYS
VB.Net allows multidimensional arrays. Multidimensional arrays are also called rectangular
arrays.

You can declare a 2-dimensional array of strings as:

Dim twoDStringArray(10, 20) As String

or, a 3-dimensional array of Integer variables:

Dim threeDIntArray(10, 10, 10) As Integer

The following program demonstrates creating and using a 2-dimensional array:

Module arrayApl

PLATFORM TECHNOLOGY CS T73 Page 19


Sub Main()
' an array with 5 rows and 2 columns
Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}
Dim i, j As Integer
' output each array element's value '
For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))
Next j
Next i
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:

a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8

INDEXERS
 An indexer is just like a method containing indexer parameter and return type. The return
type can be any valid type. An Indexer must at least have one parameter or the complier
throws an error.
 The main concept behind the indexer is to; treat the object and variables acting as a
protected or Internal.
 The keyword which is used to identify the indexer is “default” and “this”.
 “Default keyword is used when the variables act as an array.
 “this” keyword is used when the objects act As an array.
 An indexer also uses the get, set method as property uses the get, set method.
 The difference between the Indexers and Properties is, the set method of the Indexer
should have a signature. (i.e.) Parameters are passed to the set method of the Indexers.
Example for how the ‘default’ and ‘this’ keyword are used with get, set method:

PLATFORM TECHNOLOGY CS T73 Page 20


Default public property Item (ByVal index As Integer) As string
Get
Return mobiles (index -1)
End Get
Set (ByVal value As string)
Index = value
End Set
End Property
this [parameter]
Get
// Get codes here
End Get
Set (Parameter)
//Set codes here
End Set
Now let us consider the following Example:
Public class WeekDays
Private weekDays (7) As string
Public Sub New ()
weekDays (0) = “Monday”
weekDays (1) = “Tuesday”
weekDays (2) = “Wednesday”
weekDays (3) = “Thursday”
weekDays (4) = “Friday”
weekDays (5) = “Saturday”
weekDays (6) =”Sunday”
End Sub
Public Function GetDayByNumber (ByVal dayNumber As Integer) As String
Return weekDays (dayNumber)
End Function
End Class
Sub Main ()
Dim wk As New WeekDays

PLATFORM TECHNOLOGY CS T73 Page 21


Console.WriteLine (wk.GetDayByNumber (3))
End Sub
OUTPUT is: ‘Thursday’
Now let us see how we can define an indexer in the WeekDays class. In this case, indexer is
defined using the ‘default’ keyword because; we are going to make use of the variables.
Public class WeekDays
Private weekDays (7) As String
Public Sub New ()
weekDays (0) = “Monday”
weekDays (1) = “Tuesday”
weekDays (2) = “Wednesday”
weekDays (3) = “Thursday”
weekDays (4) = “Friday”
weekDays (5) = “Saturday”
weekDays (6) = “Sunday”
End Sub
Default public property WeekDay (ByVal dayNumber As Integer) As string
Get
Return weekDays (dayNumber)
End Get
Set (ByVal value As string)
weekDays (dayNumber) = value
End Set
End Property
End class
We use the indexer as the following manner; The indexer has essentially turned the WeekDays
class into an array. We can index the wk object directly.
Dim wk As New WeekDays
Console.WriteLine (wk (3))
OUTPUT is: ‘Thursday’

COLLECTIONS

PLATFORM TECHNOLOGY CS T73 Page 22


 A collection is a way of grouping and managing related objects. A collection is either
zero-based or one-based, depending on what its starting index is. The zero based
collection means that the index of the first item in the collection is Zero. One based
collection means that the index of the first item in one.
 Visual Basic .Net Collections are data structures that holds Data in different ways for
flexible operations. The important data structures in the collections are ArrayList,
HashTable, Stack and Queue etc.
 ArrayList
 ArrayList is one of the most flexible data structures from VB.Net collection. ArrayList
contains a simple list of values and very easily we can add, insert, delete, and view etc. to
do with ArrayList. It is very flexible because we can add without any size information,
that is, it can grow dynamically and also shrink.
Important Functions in ArrayList
Add: Add an item in an ArrayList
Syntax: ArrayList.add (Item)
Item – the item to be added to the array list.
Example:
Dim ItemList As New ArrayList ()
ItemList.Add (“Item4”)
Insert:Insert an item in a specified position in an ArrrayList.
Syntax: ArrayList. Insert (index, item)
Index – The position of the item in an ArrayList
Item – The Item to be inserted in the ArrayList.
Example:
ItemList.Insert (3, “item6”)
Remove: Remove an item from ArrayList.
Syntax: ArrayList. Remove (item)
Item – the item to be removed in the ArrayList
Example:
ItemList. Remove (“item 2”)
Remove At:Remove An item from a specified position.
Syntax: ArrayList. RemoveAt (index)

PLATFORM TECHNOLOGY CS T73 Page 23


Index – the position of an item to remove from an array list.
Example:
ItemList. RemoveAt (2)
Sort: Sort Items in an ArrayList.
Syntax: ArrayList.Sort ()
Stack
Stack is one of another easy method used in VB.Net. Stack follows the push – pop operations,
that is we can push Items into stack and pop it later also it follows the last in First Out (LIFO)
system. That is we can push the items into a stack and get it in reverse order. Stack returns the
last item first.

Commonly Used Methods


Push:Add (Push) an item in the stack Data Structure.
Syntax: Stack.Push (object)
Object – The item to be inserted.
Pop:Pop returns the item, last item inserted in stack.
Syntax: Stack.Pop ()
Returns the last object in the stack.
Contains:Check the object contains in the Stack.
Syntax: Stack.Contains (object)
Object – The specified object to be searched.

Queue
Queue works like First in First Out Method. The item added first in the queue is first to get out
from queue. We can Enqueue (add) items in Queue and we can dequeue (remove from queue) or
we can peek (that is get the reference of first item added in Queue) the item from Queue.
Commonly Used Functions
Enqueue:Add an item in Queue.
Syntax: Stack.Enqueue (object)
Object – the item to add in Queue.
Dequeue:Remove the oldest item from Queue (We don’t get the item later)
Syntax: Stack.Dequeue ()

PLATFORM TECHNOLOGY CS T73 Page 24


Returns – remove the oldest item and return
Peek:Get the reference of the oldest item (it is not removed permanently)
Syntax: Stack.Peek ()
Returns – Get the reference of the oldest item in the Queue.
HashTable
HashTable stores a key value pair type collection of Data. We can retrieve items from HashTable
to provide the Key. Both Key and value are objects.

Common Functions Using in HashTables


Add:To add a pair of value in HashTable
Syntax: HashTable.Add (key, value)
key – The Key value
value – The value of corresponding key
Constraint Key:Check if a specified key exist or not
Syntax: HashTable.constraintkey (key)
Key – The key value for search in HashTable
Contains value:Check the specified value exists in Hash Table.
Syntax: HashTable.containsValue (value)
Value – search the specified value in HashTable.
Remove: Remove the specified key and corresponding value
Syntax: HashTable.Remove (key)
Key – The argument key of deleting pairs.
Example Program for ArrayList:
Public class Items
Dim i As Integer
Dim ItemList As New ArrayList ()
ItemList.Add (“Item 4”)
ItemList.Add (“Item 5”)
ItemList.Add (“Item 2”)
ItemList.Add (“Item 1”)
ItemList.Add (“Item 3”)
MsgBox (“shows Added Items”)

PLATFORM TECHNOLOGY CS T73 Page 25


For i=0 to ItemList.count-1
MsgBox (ItemsList.Item (i))
Next
ItemList.Insert (3, “Item6”)
ItemList.Sort ()
ItemList.Remove (“Item 1”)
ItemList.RemoveAt (3)
MsgBox (“shows final Items the ArrayList”)
For i=0 to ItemList.count-1
MsgBox (ItemList.Item (i))
Next
End class

STRINGS
The string class represents character strings. The string Object is Immutable; it cannot be
modified once it is created. That means every time we use any operation in the string object, we
must create a new String object.
Now we are going to see the important methods used in string class.
Length ( )
Insert ( )
Index of ( )
Equals ( )
Compare ( )
Substring ( )
Split ( )
Endswith ( )
Concat ( )

String.Length ( )
Syntax: string.Length () As Integer.
The method returns the number of characters in the specified string.
Example: “This is a Test”.
Length () returns 14.

PLATFORM TECHNOLOGY CS T73 Page 26


Program:
Public class As String
str = “This is a Test”
MsgBox (str.length ())
End class
String.Insert ( )
Syntax: String.Insert (Integer ind, String str) As String
Ind – the index of the specified string to be inserted.
Str – the string to be inserted.
Example: “This is Test”.
Insert (8, “Insert”) returns “This is Insert Test”
Program:
Public class Insert
Dim str As string = “This is VB.NET Test”
Dim insStr As string = “Insert”
Dim strRes As string = str.Insert (15, insStr)
MsgBox (strRes)
End class

String.Indexof ( )
Syntax: String.Indexof (string str) As Integer
str – parameter string to check its occurrences.
Example: “This is a test”
Indexof (“Test”) returns 10.
Program:
Public class Index
Dim str As string
str = “VB.NET Top 10 Books”
MsgBox (str.Indexof (“Book”))
End class

String.Equals ( )
Syntax: String.Equals (String str1, String str2) As Boolean

PLATFORM TECHNOLOGY CS T73 Page 27


str1 – the string argument
str2 – the string argument
Example:
str1 = “Equals ()”
str2 = “Equals ()”
String.Equals (str1, str2) returns True.
Program:
Public class Equals
Dim str1 As string =”Equals”
Dim str2 As string = “Equals”
If string.Equals (str1, str2) Then
MsgBox (“Strings are not Equal ( )”)
End If
End class

String.Compare ()
Syntax: string.Compare (string str1, string str2, Boolean) As Integer
str1 – parameter string
Str2 – parameter string
Boolean TRUE/FALSE – Indication to check the string with case sensitive or without case
sensitive.
Returns 0 or <0 or >0
>0 – str1 is greater than str2.
0 – str1 is Equal to str2.
<0 – str1 is less than str2.
Program:
Public class Compare
Dim str1 As string
Dim str2 As string
str1= “vb.net”
str2= “VB.Net”
Dim result As Integer
result= string.compare (str1, str2)

PLATFORM TECHNOLOGY CS T73 Page 28


MsgBox (result)
result= string.compare (str1, str2, True)
MsgBox (result)
End class

String.substring ( )
Syntax: String.Substring (Integer StartIndex, Integer length) As string
StartIndex – The Index of the start of the substring.
length – The number of characters in the substring
Program:
Public class stringName
Dim str As string
Dim retstring As string
str =”This is substring test”
retstring =str.Substring (8, 9)
MsgBox (retstring)
End class
String.Split ( )
Syntax: String.Split (“ “) As string

Delimiter (separator)
Program:
Public class split
Dim str As string
Dim strArr ( ) As String
Dim count As Integer
str= “Vb.Net Split test”
strArr= str.split (“ “)
for count -0 to strArr.Length-1
MsgBox (strArr(count))
Next

PLATFORM TECHNOLOGY CS T73 Page 29


End class

String.Endswith ( )
Syntax: String.Endswith (string suffix) As Boolean
Suffix- the passing string for it Ends with.

Example:
“This is a Test”.
EndsWith (“Test”) returns True.
“This is a Test”.
EndsWith (“is”) returns False.

String.Concat ( )
Syntax: String.Concat (string str1, string str2) As string
str1 – parameter string
str2 – parameter string
Returns a new string with str1 concat with str2.

REGULAR EXPRESSIONS
Regular Expressions provide a language specifically for parsing and processing strings. They are
highly optimized and can be created as an instance of the Regex Class.
Regular Expression is useful for parsing and processing character based Data, particularly the
following actions can be performed.
 Replace or Delete sub strings at matches (REPLACE method).
 Parsing input text (SPLIT method)
 Extracting data from structured sources such as XML or HTML (Matches or Match
method)
 Detecting complex patterns of Characters( Is Match method)
These methods can all be used on pre-created instances for speed, they can be or executed on the
fly using static methods on the Regex class.
The relevant code is located in the System.Text.RegularExpressions Namespaces.

PLATFORM TECHNOLOGY CS T73 Page 30


There is a collection of special characters ‘ , $ ^ { [ ( | ) * + ? \’ which is used to represent special
characters, groups of characters, repeated characters of words.
To represent these without their special meaning they are escaped using the \ character.
Character escapes match single (non printable) characters or characters with special meaning.
? – Match one or Zero occurrences.
( ) – Sub expression treated as a single element.
\n – newline character
\s – white space character
\w – word character
^ - Beginning of String
& - End of the string or Line.
The various regular Expressions are:
Regex Matches
Word count
Regex (‘\w+’)
Count chars: Regex.Matches (quote,.)
Word count: Regex.Matches (quote, ‘\w+’)
Count Line: Regex.Matches (quote, ‘.+\n*’)
Regex.Compare to assembly
Match Regular Expression to string and print out all the matches.
Using Regex method Replace: substituted for * with another String.
Using Regex method Replace: Replace one string with another string.
Every word replaces by another word.
Replace first 3 digits.
String split at Commas.

Word Count Examples for Regular Expressions

Public class Tester


Sub main ( )
Dim quote As String = “ q d e w”
Do while (quote.Indexof(space (2))>=0)
quote = quote.replace (space (2), space (1))
loop
Dim wordcount As Integer= split (quote, space (1)).Length
Console.WriteLine (quote & vbNewLine & “Number of words:” &
PLATFORM TECHNOLOGY CS T73 Page 31
wordcount.ToString)
End sub
OUTPUT:
q dew No. of words: 5
Number of Words
Regex (‘\w+’)
Public class Tester
Sub main ( )
Dim quote As sting = “The important thing is not to” & - “Stop Questioning. …. Albert
Einstein”
Dim parser as New Regex (“\w+”)
Dim total Matches As Integer = parser.Matches (quote).count
Console.WriteLine (quote & vbNewLine & “ Number of Words:” & - TotalMatches.Tostring)
End Sub
End class
OUTPUT:
The Important thing is not to stop Questioning. – Albert Einstein.
Number of Words: 10

Using Regex method Replace: Replace one string with another


Public class Tester
Sub Main ( )
Console.WriteLine (New Regex (“stars”). Replace (“This sentence ends in 5 stars *****”,
“carets”))
End sub
End class
OUTPUT:
This sentence ends in 5 carets*****

Every word replaced by another word

PLATFORM TECHNOLOGY CS T73 Page 32


Public class Tester
Sub Main ( )
Console.WriteLine (Regex.Replace(“This sentence ends in 5 stars *****”, “\w+”, “word”))
End sub
End class
OUTPUT:
Word word word word word word *****

Replace first 3 digits


Public class Tester
Sub Main ( )
Console.WriteLine (New Regex (“\d”).Replace (“1,2,3,4,5,6,7,8”, “digit”, 3))
End Sub
End class
OUTPUT:
digit, digit, digit, 4,5,6,7,8.

PLATFORM TECHNOLOGY CS T73 Page 33

You might also like