1. Unit-03/Lecture-01
Object Oriented programming concept
Introduction to Object Oriented Programming (OOP) concepts in C#: Abstraction,
Encapsulation, Inheritance and Polymorphism.
All managed languages in the .NET Framework, such as Visual Basic and C#, provide full support
for object-oriented programming including encapsulation, inheritance, and polymorphism.
Encapsulation means that a group of related properties, methods, and other members are
treated as a single unit or object.
Inheritance describes the ability to create new classes based on an existing class.
Polymorphism means that you can have multiple classes that can be used interchangeably,
even though each class implements the same properties or methods in different ways.
OOP Features
Object Oriented Programming (OOP) is a programming model where programs are organized
around objects and data rather than action and logic.
OOP allows decomposition of a problem into a number of entities called objects and then builds
data and functions around these objects.
1. The software is divided into a number of small units called objects. The data and
functions are built around these objects.
2. The data of the objects can be accessed only by the functions associated with that
object.
3. The functions of one object can access the functions of another object.
CLASS:-
Class is a user defined data type. it is like a template. In c# variable are termed as instances of
classes. which are the actual objects.
Syntax in VB.NET
[ <attribute list> ] [ accessmodifier ] [Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _
Class name [ ( Of typelist ) ]
2. [ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class
Syntax of C#
Class classname
{
[Variable declaration;]
[Method declaration;]
}
Here Class is a keyword and class name is valid c# identifier. Everything inside the square
brackets is optional. It is also valid class definition.
EX:-
Class Empty
{
}
NOTE:- There are some similarities and difference between class & struct. we will discuss later.
OBJECT:-
Objects are the basic run-time entities of an object oriented system. They may represent a
person, a place or any item that the program must handle.
"An object is a software bundle of related variable and methods."
"An object is an instance of a class"
EX:-
Here This is an example of creating an object of type Rectangle.
3. Rectangle rect1=new rectangle();
Rectangle rect1=new rectangle();
Here variable 'rect1' & rect2 is object of the rectangle class.
The Method Rectangle() is the default constructor of the class. we can create any number of
objects of Rectangle class.
Constructors and Destructors in VB.NET:-
Constructors used in a class are member functions to initialize or set the objects of a
class in VB.net. They dont return any value and are defined in a Sub with a keyword
New.
• Constructors and destructors do not have return types nor can they return values.
• References and pointers cannot be used on constructors and destructors because their
addresses cannot be taken.
• Constructors cannot be declared with the keyword virtual.
• Constructors and destructors cannot be declared const, or volatile.
• Unions cannot contain class objects that have constructors or destructors.
Constructors and destructors obey the same access rules as member functions. For example, if
you declare a constructor with protected access, only derived classes and friends can use it to
create class objects.
The compiler automatically calls constructors when defining class objects and calls destructors
when class objects go out of scope. A constructor does not allocate memory for the class object
it’s this pointer refers to, but may allocate storage for more objects than its class object refers
to. If memory allocation is required for objects, constructors can explicitly call the new
operator. During cleanup, a destructor may release objects allocated by the corresponding
constructor. To release objects, use the delete operator.
Multiple constructors can be created in class with any access specifiers, by default constructors
are of Public access type.
Example:
Module Module1
Public Class Sample
4. Private a As Integer
Public Sub New(ByVal setval As Integer)
a = setval
End Sub
Public Function disp()
Return a
End Function
End Class
Sub Main()
Dim d As New Sample(5)
Console.WriteLine("Value of a is initialized to:")
Console.WriteLine(d.disp())
Console.Read()
End Sub
End Module
Result:
Value of a is initialized to:
5
Description:
In the above example, using the Constructor declared within the sub procedure New the value
of a is set to 5.
Destructors:
Destructors or finalizer is a method used to deallocate the resources of an object that are no
longer used, its invoked automatically by the VB.net environment. The keyword Overrides is
5. used with the Finalizer method.
Example:
Protected Overrides Sub Finalize()
Console.WriteLine("Calling Destructor")
Ens Sub
Abstract Class:-
Abstract Classes in VB.net are classes that cannot be instantiated, but can implement any
number of members. The Abstract Classes are declared using the keyword MustInherit.
Overideable members should be declared inside the abstract class using the keyword
MustOverride that are instantiated in the derived class by overriding them.
Ex: A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD
screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't
need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna,
speaker’s works. You just need to know how to operate the laptop by switching it on. Think
about if you would have to call to the engineer who knows all internal details of the laptop
before operating it. This would have highly expensive as well as not easy to use everywhere
by everyone.
Example:
Module Module1
Public MustInherit Class student
Public id As Integer
Public Function Add() As Integer
Dim i, j As Integer
i = 100
j = 200
6. Console.WriteLine("Result:" & (i + j))
End Function
Public MustOverride Sub Disp()
End Class
Class Shed
Inherits student
Public Overrides Sub Disp()
Console.WriteLine("Instantiating the abstract member
function disp() in the derived class.")
End Sub
End Class
Sub Main()
Dim obj As New Shed
obj.Add()
obj.Disp()
Console.Read()
End Sub
End Module
Result:
Result:300
Instantiating the abstract member function disp()
in the derived class
Description:
In the above example, the Absract class 'student' acts as a base class and the abstract member
7. of the class 'Disp()' is overidden inside the derived class Shed.
Unit-03/Lecture-02
Object Oriented programming concept
Encapsulation:
Encapsulation is a process of binding the data members and member functions into a single
unit. Wrapping up a data member and a method together into a single unit (in other words
class) is called Encapsulation.
Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data
related to an object into that object.
Encapsulation is like your bag in which you can keep your pen, book etcetera. It means this is
the property of encapsulating members and functions.
class Bag
{
book;
pen;
ReadBook();
}
Encapsulation means hiding the internal details of an object, in other words how an object does
something.
Encapsulation prevents clients from seeing its inside view, where the behaviour of the
abstraction is implemented.
Encapsulation is a technique used to protect the information in an object from another object.
8. Hide the data for security such as making the variables private, and expose the property to
access the private data that will be public.
Example for encapsulation is class. A class can contain data structures and methods.
Consider the following class
public class Aperture
{
public Aperture ()
{
}
protected double height;
protected double width;
protected double thickness;
public double get volume()
{
Double volume=height * width * thickness;
if (volume<0)
return 0;
return volume;
}
}
In this example we encapsulate some data such as height, width, thickness and method Get
Volume. Other methods or objects can interact with this object through methods that have
public access modifier
The Differences between Abstraction and Encapsulation:-
9. AbstractioAbstractionsaction Encapsulation
1. Abstraction solves the problem at
the design level.
1. Encapsulation solves the problem in the
implementation level.
2. Abstraction hides unwanted data
and provides relevant data.
2. Encapsulation means hiding the code and
data into a single unit to protect the data
from the outside world.
3. Abstraction lets you focus on what
the object does instead of how it does
it
3. Encapsulation means hiding the internal
details or mechanics of how an object does
something.
4. Abstraction: Outer layout, used in
terms of design.For example:An
external of a Mobile Phone, like it has
a display screen and keypad buttons to
dial a number.
4. Encapsulation- Inner layout, used in terms
of implementation.
For example: the internal details of a Mobile
Phone, how the keypad button and display
screen are connected with each other using
circuits.
Polymorphism:-
When a message can be processed in different ways is called polymorphism. Polymorphism
means many forms.
Polymorphism is one of the fundamental concepts of OOP.
Polymorphism provides following features:
• It allows you to invoke methods of derived class through base class reference during
runtime.
• It has the ability for classes to provide different implementations of methods that are
called through the same name.
Polymorphism is of two types:
10. 1. Compile time polymorphism/Overloading
2. Runtime polymorphism/Overriding
Compile Time Polymorphism
Compile time polymorphism is method and operators overloading. It is also called early binding.
In method overloading method performs the different task at the different input parameters.
Runtime Time Polymorphism
Runtime time polymorphism is done using inheritance and virtual functions. Method overriding
is called runtime polymorphism. It is also called late binding.
When overriding a method, you change the behavior of the method for the derived class.
Overloading a method simply involves having another method with the same prototype.
Caution: Don't confused method overloading with method overriding, they are different,
unrelated concepts. But they sound similar.
Method overloading has nothing to do with inheritance or virtual methods.
Following are examples of methods having different overloads:
void area(int side);
void area(int l, int b);
void area(float radius);
Practical example of Method Overloading (Compile Time Polymorphism)
using System;
namespace method_overloading
{
class Program
{
11. public class Print
{
public void display(string name)
{
Console.WriteLine ("Your name is : " + name);
}
public void display(int age, float marks)
{
Console.WriteLine ("Your age is : " + age);
Console.WriteLine ("Your marks are :" + marks);
}
}
static void Main(string[] args)
{
Print obj = new Print ();
obj.display ("George");
obj.display (34, 76.50f);
Console.ReadLine ();
}
}
}
Interfaces: -
12. 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. Intefaces 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))
13. End Function
End Class
Sub Main()
Dim obj1 As New first
Dim obj2 As New second
obj1.Add(10)
obj2.Add(50)
Console. Read()
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.
S.NO RGPV QUESTIONS Year Marks
Q.1 What are the constructors? How they are useful?
Also explain overloading constructor.
June2009 10
Q.2 Write the brief on the following: Inheritance Dec2010,Dec2011 04
Q.3 Explain the object oriented concept in VB.NET. June2010 10
14. Unit-03/Lecture-03
Classes and Objects: Types value type model, structure
Structures in VB.NET:-
Visual Basic .NET, structures are similar to classes in that they associate one or more members
with each other. A Structure is a value type. Its data is contained directly inside its bytes.
Integers, Booleans and Date Times are built-in Structures. When we pass a Structure to a
method, its bytes are copied each time. Structure is the value type data type that can contain
variables, methods, properties, events and so on. It simplifies the program and enhances
performance of code in C# programming.
The structure encapsulate small group of related variables inside a single user-defined data
type. It improves speed and memory usage and also enhances performance and clarity of your
code.
Creating Structures
In Visual Basic .NET, structures are similar to classes in that they associate one or more
members with each other. A structure is also similar to a class in that it can contain member
data, properties, methods, and events. Structures do, however, have distinct differences from
classes:
• Structures aren't inheritable.
• Structures are implicitly derived from System.ValueType.
• A variable of a structure type directly contains its own copy of data.
• Structures are never terminated. The CLR doesn't call the Finalize method on a
15. structure.
• Structures require parameters when they have nonshared constructors. However, all
structures implicitly have a public New() constructor without parameters that initializes
the members to their default value.
• Declarations of a structure's data members can't include initializers.
• The default access for members declared with the Dim statement is public.
• Members can't be declared Protected in a structure.
• Equality testing must be performed with a member-by-member comparison.
• Structures can't have abstract methods.
A struct consists of three parts: the keyword struct, an optional identifier called a tag, and the
member data fields of the struct listed inside parentheses. The tag name is optional and can be
left out.
The general syntax for a struct with tag is:
struct tagname {
datatype1 name1;
datatype2 name2;
datatype3 name3;
...
} variable_name;
EX.:-
Private Structure employee
Public givenName As String
Public familyName As String
Public phoneExtension As Long
Private salary As Decimal
16. Public Sub giveRaise(raise As Double)
salary *= raise
End Sub
Public Event salaryReviewTime()
End Structure
Structures Vs Classes:-
Structure Class
Value type Reference type
Supports data members, code
members (methods) and events
Supports data members, code members
(methods) and events
Can not inherit Supports inheritance
Preferable when you perform
large number of operations on
each instance
Preferable when you need to initialize
one or more members upon creation
Can not control initialization using
structure variable
Can have parameterized constructors
Less flexible, limited event
handling support
More flexible, unlimited event handling
support
S.NO RGPV QUESTIONS Year Marks
Q.1
17. Unit-03/Lecture-04
Enumeration, Object reference model
Enumeration:-
Enumeration in is a collection of related set of constants that are declared using the keyword
Enum Statement. All the members are of "enum" datatype and will have an numeric value that
start with '0' for first element. The enum keyword is used to declare an enumeration, a distinct
type that consists of a set of named constants called the enumerator list.
Usually it is best to define an enum directly within a namespace so that all classes in the
namespace can access it with equal convenience. However, an enum can also be nested within
a class or struct. By default, the first enumerator has the value 0, and the value of each
18. successive enumerator is increased by 1. For example, in the following enumeration, Sat is 0,
Sun is 1, Mon is 2, and so forth.
enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
Enumerators can use initializers to override the default values, as shown in the following
example.
num Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
In this enumeration, the sequence of elements is forced to start from 1 instead of 0. However,
including a constant that has the value of 0 is recommended. For more information, see
Enumeration Types (C# Programming Guide).
Every enumeration type has an underlying type, which can be any integral type except char. The
default underlying type of enumeration elements is int. To declare an enum of another integral
type, such as byte, use a colon after the identifier followed by the type, as shown in the
following example.
enum Days : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
A variable of type Days can be assigned any value in the range of the underlying type; the values
are not limited to the named constants.
Syntax:
Enum enumeration name [ As data type ]
member list
End Enum
In the above syntax the enumeration name provides a unique name for the enumeration, data
type can be specified if required, member list lists the members of the enumeration.
Example:
Module Module1
Enum Fruits
19. Orange = 1
Apple = 2
Guava = 3
End Enum
Sub Main()
Console.WriteLine("First Fruit is::"
& Fruits.Orange.ToString())
Console.WriteLine("Second Fruit is::"
& Fruits.Apple.ToString())
Console.WriteLine("Third Fruit is::"
& Fruits.Guava.ToString())
Console.ReadLine()
End Sub
End Module
Result:
First Fruit is:: Orange
Second Fruit is:: Apple
Third Fruit is:: Guava
Description:
In the above example, three enumeration members are listed under the enumeration name
Fruits that have a numeric value starting from '1'.
Object reference model:-
The object−reference model specifically ensures that objects are accessed only via a reference
variable that points to a location in memory where the object is stored. To best illustrate how
20. Unit-03/Lecture-05
Classes and Objects: Interfaces
Classes:-
.NET programmer without continuously thinking about your applications in terms of classes and
objects. Thinking in terms of classes and objects (in other words, thinking in terms of
object−oriented programming) means thinking about the bigger picture and not only about
code.This is not an easy thing to do and takes many years of experience. It means thinking
about how you canorganize your objects as a cohesive systemin much the same way as your
body is organized as a cohesive system.
Thinking in terms of OOP need not detract from cohesion at the method level, nor how brilliant
you might be at writing method code. Being able to design and implement good OO design and
still write tight methods is what makes a brilliant programmer. In fact, I have an obsession with
objects, and yet that does not stop me from doing my best to optimize methods to as few lines
of code as possible. After more than a decade in this business, I still struggle to come up with
clean, stable OO design. You'll find that as you master smaller
systems, the bigger ones take you back to square one.
The world of classes and objects, object−based programming, and object−oriented software
development using Visual Basic .NET.
Getting the Semantics Correct:
Before we get cracking, you should be clear on the difference between classes and objects
And types, because we all have the habit of using the terms loosely to mean the same thing.
Both classes and objects may be thought of as types, which are correct; however, classes and
objects have very different roles in your application design and construction. We touched a
little on this in the last chapter.
A class is a blueprint, a template, a specification, a pattern, or any other founding definition of
an object.Objects absolutely depends on classes; without classes, you don't have objects. This
should be clear from.
Classes are almost always a design−time construct, whereas objects can only exist at run time.
21. A process called instantiation, as indicated in manifests objects. In other words, when you need
an object during the course of a running application, you must create an instance
of the class, which is an object. You can typically create many instances of a class, but you can
also program a class in such a way that only one instance of it can be created. This class is called
a singleton. Calling class constructors creates objects. The ultimate constructor of a class is the
New method.
Type and class mean the same thing to many people, and in many respects, I use these terms
interchangeably in this booknot a problem. However, if you really want to excel at this, it will
pay dividends to realize the subtle difference between the word "class" and the word "type."
Semantics and Notation:-
Before we can design classes (or types), it is vital that we all talk the same language. Trying to
describe classes and objects in code is not impossible but it is as cumbersome as taking a dip in
a tide pool with a windbreaker and gumboots. Many modeling languages and notations have
thus been introduced down the ages of OO engineering. The most popular ones are Booch
notation, Object Model Technique (OMT), and Unified Modeling Language(UML).
UML has emerged as the principal class design and object modeling language in use today;
much of its constructs and elements really derive from several earlier modeling languages and
notation that have survived the past few decades.You don't need to be fluent in UML, but you
do need to know UML notation to define and model classes and applications. This is what we
are going to tackle in the next section. A full−blown discussion of UML and, for
that matter, object−oriented analysis and design using UML.
Modelling:-
Architects build models, in the form of miniature constructions of the actual buildings, houses,
or complexes they are going to construct. Landscapers build models, in the form of miniature
gardens that represent, almost identically, the land they intend to sculpt. Boat builders build
miniature boats, complete with engines, tiny plastic crew members, bunk beds, and so on.
A model can be an almost identical representation of the actual thing to be built. A model omits
all the nonessential details, although some model builders can get carried away. Some
architects will build models of shopping centers and malls, and add real miniature lakes and
waterfalls.
Object Modelling Technique (OMT):
The object model is the most abstract of the models because it describes the structure of the
22. objects in your software. An object model (and you could call the entire .NET Framework one
huge object model) identifies the objects and the relationships between them. It also defines
their attributes and what they do. Even though we will be talking about classes, the net result is
a system of objects.
When we talk about an object model framework, we mean the framework into which both the
dynamic and functional models can be placed. Life can be considered one huge object model.
The natural object models in nature, in us, comprise the cohesive objects that make up our
existence from the highest level going all the way down to the molecules and subatomic
matter.
Object models are the most abstract of the three models. Object models provide that so−called
mile−high view of the system. No matter the problems we are trying to solve or the applications
we are trying to build, the object model should be easy to understand and its concepts should
be easy to grasp. If you are modeling a business problem, your models should reflect concepts
that business people can understand. The terms and visuals of the business−problem model
should be familiar to business people. The same strategy applies to
engineering problems, scientific problems, and so on. Object models for software systems are
built using graphical notation languages that render object diagrams that will ultimately
represent class libraries and their elements. Later in this chapter, we will explore class and
object diagrams in more depth.
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. Intefaces 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.
Interfaces define the properties, methods, and events that classes can implement. Interfaces
allow you to define features as small groups of closely related properties, methods, and events;
this reduces compatibility problems because you can develop enhanced implementations for
your interfaces without jeopardizing existing code. You can add new features at any time by
developing additional interfaces and implementations.
There are several other reasons why you might want to use interfaces instead of class
inheritance:
23. Interfaces are better suited to situations in which your applications require many possibly
unrelated object types to provide certain functionality.
Interfaces are more flexible than base classes because you can define a single implementation
that can implement multiple interfaces.
Interfaces are better in situations in which you do not have to inherit implementation from a
base class.
Interfaces are useful when you cannot use class inheritance. For example, structures cannot
inherit from classes, but they can implement interfaces.
Declaring Interfaces:-
Interface definitions are enclosed within the Interface and End Interface statements. Following
the Interface statement, you can add an optional Inherits statement that lists one or more
inherited interfaces. The Inherits statements must precede all other statements in the
declaration except comments. The remaining statements in the interface definition should be
Event, Sub, Function, Property, Interface, Class, Structure, and Enum statements. Interfaces
cannot contain any implementation code or statements associated with implementation code,
such as End Sub or End Property.
In a namespace, interface statements are Friend by default, but they can also be explicitly
declared as Public or Friend. Interfaces defined within classes, modules, interfaces, and
structures are Public by default, but they can also be explicitly declared as Public, Friend,
Protected, or Private.
Interface IAsset
Event ComittedChange(ByVal Success As Boolean)
Property Division() As String
Function GetID() As Integer
End Interface
Example:
Module Module1
Public Interface Interface1
24. 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()
25. Unit-03/Lecture-06
Exception handling and Classes
Exception handling:-
Exceptions Handling are errors that are triggered at runtime, that are handled in VB.net using
structured error handling with the Try..Catch..Finally statement. The On erro goto, On Error
Resume Next statement is used for unstructured error handling.
The exceptions can be handled in the Try..Catch..finally using the Built-in exception handling
methods.
• Try Catch and Finally keywords.
• Giving the user information about an exception.
• Catching only certain exceptions.
The Try, Catch and Finally keywords are usually refered to as Error Handling. Handling
exceptions with these methods will stop your application from recieving runtime errors (errors
encountered during running the application) caused by exceptions.
When you handle these errors, VB.NET gives you the ability to get a wealth of information
about the exception and ways to let your application correspond according to them. Before we
get into getting exception information, let’s talk the complete basics.
• Try - The Try keyword will tell the compiler that we want to handle an area for errors.
The Try keyword must have an Catch method, and must be encapsulated in an End Try
statement.
• Catch - The Catch keyword tells the application what to do if an error occurs. It will stop
the application from crashing, and let the application do the rest.
• Finally - The Finally keyword will occur regardless if the Try method worked successfully
or a Catch method was used. The Finally keyword is optional.
Syntax:- Try
Catch ex As Exception
Finally
End Try
26. Structured Exception Handling:-
Structured exception handling tests specific pieces of the code and, as exceptions occur, adapts
your exception-handling code to the circumstances that caused the exception. It is significantly
faster in large applications than unstructured exception handling and allows more flexible
response to errors as well as greater application reliability.
The Try...Catch...Finally control structure is fundamental to structured exception handling. It
tests a piece of code, filters exceptions created by the execution of that code, and reacts
differently based on the type of thrown exception.
The Try...Catch...Finally block
Try...Catch...Finally control structures test a piece of code and direct how the application
should handle various categories of error. Each of the structure's three constituent parts plays a
specific role in this process.
Unstructured Exception Handling:-
Unstructured exception handling is implemented using the Err object and three statements: On
Error, Resume, and Error. The On Error statement establishes a single exception handler that
catches all thrown exceptions; you can subsequently change the handler location, but you can
only have one handler at a time. The method keeps track of the most recently thrown
exception as well as the most recent exception-handler location. At entry to the method, both
the exception and the exception-handler location are set to Nothing.
To generate a run-time error in your code, use the Raise method. Whenever an Exit Sub, Exit
Function, Exit Property, Resume or Resume Next statement occurs within an error-handling
routine, the Err object's properties are reset to zero or zero-length strings. Using any of these
outside an error-handling routine does not reset its properties. If you need to do so, you can
use the Clear method to reset the Err object.
Example1:
Module Module1
Sub Main()
Dim a(3) As Integer
Try
27. Unit-03/Lecture-07
Collections and Arrays
Collections:-
A collection is a way of grouping a set of related items. Many different types of collections exist.
Predefined collections are used in Visual Basic applications for many purposes, for example the
Control.ControlCollection on a Form, returned by the form's Controls property. You can also
create your own collections to organize and manipulate objects.
Collections are a good way to keep track of objects that your application might need to
dynamically create and destroy. The following code fragment shows how you can use the Add
Method of a Visual Basic Collection Object to keep a list of widget objects the user has created.
Collection classes are specialized classes for data storage and retrieval. These classes provide
support for stacks, queues, lists, and hash tables. Most collection classes implement the same
interfaces.
Collection classes serve various purposes, such as allocating memory dynamically to elements
and accessing a list of items on the basis of an index, etc. These classes create collections of
objects of the Object class, which is the base class for all data types in VB.Net.
The following code fragment shows how you can use the Add Method of a Visual
28. Basic Collection Object to keep a list of widget objects the user has created.
‘Declare and create the Collection object.
Public widgetColl As New Microsoft.VisualBasic.Collection()
‘Create a new widget and add it to the widgetColl collection.
Private Sub makeAWidget()
Dim tempWidget As New widget()
widgetColl.Add(tempWidget)
End Sub
The Visual Basic Collection object stores all its elements as type Object, so you can add an item
of any data type. There is no safeguard against inappropriate data types being added. To avoid
this limitation, you can use the generic collections of the System. Collections.
A Visual Basic Collection Object stores each item with data type Object. Therefore, the range of
data types you can add to a Collection object is the same as the range of data types you can
store in an Object variable. This includes standard data types, objects, and arrays, as well as
user-defined structures and class instances.
Various Collection Classes and Their Usage:-
Class Description and Useage
29.
30. retrieve items.
• You might want to add an item to a collection as soon as the item is newly created or
obtained, such as a new customer.
• You might want to delete an item from a collection when it no longer belongs in the
collection, for example when an employee leaves your company.
• You might want to retrieve an item from a collection to edit its contents, for example to
change a student's telephone number.
To add an item to a collection
Use the Add Method (Collection Object) and specify the item by its Key.
object.Add(Item, Key [, {Before | After}])
For example, to add a work order object to a collection of work orders using the work
order's ID property as its key, you can make the following call.
To delete an item from a collection
Use the Remove Method (Collection Object) and specify the item by either its Index or
its Key.
object.Remove({Index | Key})
The Index argument is the position of the item you want to delete.
To retrieve an item from a collection
Use the Item Property (Collection Object) and specify the item by either its Index or its
Key.
variable = object.Item({Index | Key})
As with the Remove method, the Index argument is the item's position in the collection,
and the Key argument is the string used when the item was added.
Arrays:-
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
31. 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.
Arrays in VB.net are declared using the Dim statement, but by using the access specifiers
Public, Private, Static, Protected the scope of usage of arrays can be controlled within the code.
Following are the basic types of arrays used in VB.net
• Single Dimension Array
• Multi Dimension Array
• Jagged Array
• Dynamic Arrays
One Dimensional Array
One dimensional array stores all the elements of an array in a single row starting
with index 0 until the end of the array.
Example:
Module Module1
Sub Main()
Dim ary(4) As Integer
Dim j As Integer
Dim i As Integer
ary = New Integer() {1, 2, 2, 3}
32. For i = 0 To ary.GetUpperBound(0)
j = ary(i) + j
Next
System.Console.Write("The Sum of Array is::")
System.Console.WriteLine(j)
Console.ReadLine()
End Sub
End Module
Result:
The Sum of Array is:8
Description:
In the above example, one dimensional array of type Integer ary is declared with four elements.
Using a loop with the starting value of '0' to upperbound value of the array got using the
GetBound(0), the sum of array is calculated.
Multi Dimensional Array
Multidimensional array is an array in which each element acts as an array that are
represented as row and columns.
Example:
Module Module1
Sub Main()
Dim arr(3, 2) As String
Dim i As Integer
Dim j As Integer
33. arr(1, 1) = "COSCO"
arr(1, 2) = "Football"
arr(2, 1) = "NIKE"
arr(2, 2) = "Boots"
arr(3, 1) = "ADDIDAS"
arr(3, 2) = "Spikes"
For i = 1 To 3
For j = 1 To 2
System.Console.WriteLine(arr(i, j))
Next
Next
Console.ReadLine()
End Sub
End Module
Result:
COSCO
Football
NIKE
Boots
ADDIDAS
Spikes
Description:
In the above example using a multi dimensional array of string datatype, all the elements are
34. retreived using a loop and displayed in the console. This array can be also said to be a
Rectangular Array since it contains the same number of rows and columns.
Unit-03/Lecture-08
Arrays types and other data structure
Arrays types:-
Jagged Array:-
Jagged Array is also an Multi Dimensional array with different number of rows and
column elements. This type of array can be used to reduce the space occupied by an
array, since all rows don't have equal number of columns.
Example:
Module Module1
35. Sub Main()
Dim one() As Integer = {1, 2, 3}
Dim two() As Integer = {3, 4, 5, 6, 7}
Dim jag()() As Integer = {one, two}
Dim i, j As Integer
For i = 0 To jag.Length - 1
For j = 0 To jag(i).Length - 1
Console. Write((jag(i)(j)))
Next
Console.WriteLine()
Next
Console.ReadLine()
End Sub
End Module
Result:
123
34567
Description:
In the above example jag is a jagged array that has different number of rows and columns
elemenst referenced using two other arrays one and two.
Dynamic Array
Dynamic arrays are array that are declared using a Dim statement with blank
parenthesis initially and are dynamically allocated dimensions using the Redim
statement.
36. Example:
Module Module1
Sub Main()
Dim a() As Integer = {2, 2}
Dim i, j As Integer
Console.WriteLine("Array before Redim")
For i = 0 To a.GetUpperBound(0)
Console.WriteLine(a(i))
Next
ReDim Preserve a(5)
Console.WriteLine("Array after Redim")
For j = 0 To a.GetUpperBound(0)
Console.WriteLine(a(j))
Next
Console.ReadLine()
End Sub
End Module
Result:
Array before Redim
2, 2
Array after Redim
2,2, 0, 0, 0
37. Next
Console.ReadLine()
End Sub
End Module
Result:
Array before Redim
2, 2
Array after Redim
2,2, 0, 0, 0
Description:
In the above Dynamic Array example, the array a initially declared with 2 elements, then using
the ReDim statement a dimension of 5 is assigned. The Preserve keyword is used to preserve
the existing elements intact.
Other data structure:-
Searching and Sorting Arrays:-
The simplest array search algorithm is typically known as a sequential search, because you
iterate through each element in the array, one element at a time in sequence, to find the
element that matches what you are looking for. The following code does exactly that, using a
For loop to "iterate" through the array. The example looks for a specific value in the array and
then returns the index value holding the matching variable.
Sub WhatIndex(ByRef array() As Integer, ByVal ArrayVal As Integer)
Dim intI As Integer
For intI = 0 To UBound(array)
If ArrayVal = array(intI) Then
Console.WriteLine("Found the value {0} at index {1}", _
38. ArrayVal, intI)
End If
Next intI
End Sub
This method receives the reference of the array to iterate through. It uses the ForNext loop to
iterate through the array until the variable passed to the ArrayVal parameter matches the value
of the element in the array.
The BinarySearch Method:- The Binary Search method is simple to use. It essentially looks for
the first occurrence of the element value you specify and returns an Integer representing the
index value of the element holding the first occurrence of the value. If the method is
unsuccessful, it will return 1 to the caller.
The following code declares an array of type Double and then searches for the occurrence of
4.0:
Dim sAlarms() As Double = New Double(3) {1.3, 2.5, 3.0, 4.0}
Console.WriteLine("Found at index: {0}", _
sAlarms2.BinarySearch(sAlarms2, 4.0)
The method returns 3 to the caller, which just so happens to be the UBound element of this
SAlarms array. The Binary Search algorithm can be used for a variation of array search criteria,
but you must remember to sort the array first for the best performance. Here's why: When you
perform a binary search, the algorithm bisects the array it searches and then checks the last
value in the first part of the array. If the value found is less than the search value we are looking
for, the algorithm will only search the second part. If it turns out that
the value is more than the search value, then the value we are looking for might be in the first
part of the array in which case the second part of the array is ignored. This is why the algorithm
is called binary search; it has nothing to with the binary representation of the value.
The method makes the assumptions just described because it knows that the data in the array
is sorted and that if an item is not in one part of the array, it must be in the other. Thus, only
part of the array is searched, which is why binary search is so fast.The method is overloaded as
follows:
39. BinarySearch(Array, Object) As Integer
BinarySearch(Array, Object, IComparer) As Integer
BinarySearch(Array, Integer, Integer, Object) As Integer
BinarySearch(Array, Integer, Integer, Object, IComparer) As Integer
While the Array. Binary Search method is documented to require you to first sort the array, it
does not specify the behavior of the method if it encounters an unsorted array. The following
example seeds an array with values and then sets BinarySearch on it before and after sorting.
The results are not surprising.
Example:
Sub FindMyValue()
Dim sArray() As Integer = {12, 82, 23, 44, 25, 65, 27}
Debug.WriteLine(Array.BinarySearch(sArray, 27))
End Sub
Bubble Sort:-
The bubble sort is widely used to sort small arrays and is very easy to work with. It gets its
name from the idea that the smaller values "bubble" to the top, while the heavier ones sink
(which is why it's also known as “sinking sort"). And if you watch the values move around in
your debugger's Locals windows you see why it's called bubble sort.
The Print Array method is called twice to show the array both unsorted and sorted. The
bubble sort is called before the second call to PrintArray to display the sorted list out to the
console:
Public Module BubbleTest
Dim Alarms() As Integer = New Integer() {134, 3, 1, 23, 87, 342, 2, 9}
Sub Main()
PrintArray(Alarms)
BubbleSort(Alarms)
40. PrintArray(Alarms)
Console.ReadLine()
End Sub
Public Overloads Sub PrintArray(ByRef Array() As Integer)
Dim result As String
Dim intI As Integer
For intI = 0 To UBound(Array)
result = CStr(Array(intI))
Console.WriteLine(result)
Next intI
Console.WriteLine("−")
End Sub
Public Sub BubbleSort(ByRef Array() As Integer)
Dim outer, inner As Integer
For outer = 0 To Array.Length 1
For innerI = 0 To Array.Length 2
If (Array(innerI) > Array(innerI + 1)) Then
Transpose(Array, innerI, innerI + 1)
End If
Next innerI
Next pass
End Sub
Public Overloads Sub Transpose(ByRef Array() As Integer, ByVal first _
As Integer, ByVal second As Integer)
41. Dim keep As Integer
Keep = Array(first)
Array(first) = Array(second)
Array(second) = keep
End Sub
End Module
Output: 134, 3,1,23, 87, 342, 2, 9
−−−
1,2,3,9,23,87,134,342
S.NO RGPV QUESTIONS Year Marks
Q.1 Explain array list.How items are added and deleted from
an array list? Use suitable example.
June2009 10
Q.2 Write a VB.NET program using one dimensional array
and convert element in reverse order.
Dec2011 10
Q.3 Write a program that initializes a 2D arrow of 4 of 5 with
number and displays the sum of all rows, columns and
the entire matrix.
Dec2013 07
42. Unit-03/Lecture-09
Value type and reference type: Boxing and Unboxing
Value type and reference type:-
In Visual Basic, data types are implemented based on their classification. The Visual Basic data
types can be classified according to whether a variable of a particular type stores its own data
or a pointer to the data. If it stores its own data it is a value type; if it holds a pointer to data
elsewhere in memory it is a reference type.
All the Types in .Net are in one of two categories - they are either value types or reference
types.
For our purposes we'll simplify things. We'll say that value types are stored in Stack memory,
which is fast but limited in size. Compared to reference types, which are stored in Heap
memory, which is slower but larger. (Value types can live on the heap too, if they are part of a
reference type, but we are just thinking about variables declared locally inside procedures to
keep things simple).
A variable is just a label we use as programmers to identify some value on the stack.
Value types:-
Value types are stored directly on the stack, either within an array or within another type; their
storage can only be accessed directly. Because value types are stored directly within variables,
their lifetime is determined by the lifetime of the variable that contains them. When the
location containing a value type instance is destroyed, the value type instance is also destroyed.
Value types are always accessed directly; it is not possible to create a reference to a value type.
Prohibiting such a reference makes it impossible to refer to a value class instance that has been
destroyed. Because value types are always NotInheritable, a variable of a value type always
contains a value of that type. Because of this, the value of a value type cannot be a null
reference, nor can it reference an object of a more derived type.
A data type is a value type if it holds the data within its own memory allocation. Value types
include the following:
• All numeric data types
• Boolean , Char, and Date
43. • 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
Reference types
Reference types are stored on the run-time heap; they may only be accessed through a
reference to that storage. Because reference types are always accessed through references,
their lifetime is managed by the .NET Framework. Outstanding references to a particular
instance are tracked and the instance is destroyed only when no more references remain. A
variable of reference type contains a reference to a value of that type, a value of a more
derived type, or a null reference. A null reference is a reference that refers to nothing; it is not
possible to do anything with a null reference except assign it.
A reference type contains a pointer to another memory location that holds the data. Reference
types include the following:
• String
• All arrays, even if their elements are value types
• Class types, such as Form
• Delegates
The following example shows the difference between reference types and value type
Imports System
Class Class1
Public Value As Integer = 0
End Class
Module Test
Sub Main()
Dim val1 As Integer = 0
Dim val2 As Integer = val1
val2 = 123
Dim ref1 As Class1 = New Class1()
Dim ref2 As Class1 = ref1
ref2.Value = 123
Console.WriteLine("Values: " & val1 & ", " & val2)
Console.WriteLine("Refs: " & ref1.Value & ", " & ref2.Value)
44. End Sub
End Module
The following example shows how Object can be used with both value types and reference
types:
Imports System
Class Class1
Public Value As Integer = 0
End Class
Structure Struct1
Public Value As Integer
End Structure
Module Test
Sub Main()
Dim val1 As Object = New Struct1()
Dim val2 As Object = val1
val2.Value = 123
Dim ref1 As Object = New Class1()
Dim ref2 As Object = ref1
ref2.Value = 123
Console.WriteLine("Values: " & val1.Value & ", " & val2.Value)
Console.WriteLine("Refs: " & ref1.Value & ", " & ref2.Value)
End Sub
End Module
The output of the program is:
Values: 0, 123
Refs: 123, 123
Boxing and Unboxing:-
Boxing and unboxing is a essential concept in VB.NET's type system. With Boxing and unboxing
45. one can link between value-types and reference-types by allowing any value of a value-type to
be converted to and from type object. Boxing and unboxing enables a unified view of the type
system wherein a value of any type can ultimately be treated as an object. Converting a value
type to reference type is called Boxing.Unboxing is an explicit operation.
VB.NET provides a "unified type system".
Boxing and unboxing is an important concept in VB.NET's type system. With Boxing and
Unboxing one can link between value-types and reference-types by allowing any value of a
value-type to be converted to and from type object.
Boxing
A boxing conversion permits any value-type to be implicitly converted to the type object or to
any interface-type implemented by the value-type.
Boxing a value of a value-type consists of allocating an object instance and copying the value-
type value into that instance.
• Boxing is a mechanism in which value type is converted into reference type.
• It is implicit conversion process in which object type (super type) is used.
• In this process type and value both are stored in object type
Unboxing
Unboxing conversion of an object box to a value-type G consists of executing the expression
((G_Box) box).value.
• Unboxing is a mechanism in which reference type is converted into value.
• It is explicit conversion process.
Program to show Boxing and Unboxing:
Module Module1
Sub Main()
Dim i As Integer = 10
Dim j As Integer
' boxing
Dim o As Object
o = i
'unboxing
j = CInt(o)
46. Console.WriteLine("value of o object : " & o)
Console.WriteLine("Value of j : " & j)
Console.ReadLine()
End Sub
End Module
Output of above program:
Value of o object=10
Value of j=10
S.NO RGPV QUESTIONS Year Marks
Q.1 Explain the Boxing. Dec2011 05
Q.2 Explain the following terms with suitable example:
i)Value type
ii)Reference type
Dec2009 10