Unit 3
Unit 3
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.
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.
Double 8 bytes
-1.79769313486231570E+308 through -
4.94065645841246544E-324, for negative values
4.94065645841246544E-324 through
1.79769313486231570E+308, for positive values
Single 4 bytes
-3.4028235E+38 through -1.401298E-45 for negative
values;
1.401298E-45 through 3.4028235E+38 for positive
values
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
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.
Where,
accessmodifier defines the access levels of the variables, it has values as - Public, Protected,
Friend, Protected Friend and Private. 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.
Each variable in the variable list has the following syntax and parts –
Where,
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.
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
When the above code is compiled and executed, it produces the following result:
FIELDS
Fields, also known as data members, hold the internal state of an object.
Field declarations include an access modifier, which determines how visible the field is
from code outside the containing class definition.
Two instances can have different values in their corresponding fields. For example:
emp1.EmployeeNumber = 10
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
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(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:
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:
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).
[ method_body ]
End Sub
[ 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
'box 2 specification
Box2.setLength(12.0)
Box2.setBreadth(13.0)
Box2.setHeight(10.0)
'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:
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.
TYPES:
A property can have any data type.
It does not need to be an Integer.
It can be a 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
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.
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.
Total area: 35
POLYMORPHISM
It is the ability of classes to provide different implementation of methods that are called
by same name.
Thus polymorphism refers to being able to use many form of a type without regard to the
details.
Runtime Polymorphism.
Method Overloading means having two or more methods with the same name but with
different parameters.
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
Method Overriding means having two or more methods with the same name, same
parameters but with different implementation.
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
Example:
Module Module1
Class Over
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.
The operators that can be defined on your class or structure are as follows:
Unary operators:
+ - Not IsTrue IsFalse CType
Binary operators:
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
Sub Main()
Dim obj1 As New first
Dim obj2 As New second
obj1.Add(10)
obj2.Add(50)
Console.Read()
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 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.
The lowest address corresponds to the first element and the highest address to the last
element.
You can also initialize the array elements while declaring the array. For example,
The elements in an array can be stored and accessed by using the index of the array. The
following program demonstrates this:
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.
Module arrayApl
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:
COLLECTIONS
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 ()
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.
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
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)
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
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.