Visual Programing1 Notes v2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

INSTITUTE OF BUSINESS & MANAGEMENT SCIENCES/CS

THE UNIVERSITY OF AGRICULTURE PESHAWAR


AMIR MUHAMMAD KHAN CAMPUS MARDAN

Program: BS (CS)-VI
Course Title: Visual Programming - I
Course Code: CS-515
Course Hours: 03
Total Week: 16
Total Credit Hours: 48
Instructor: Noorul Wahab

Course Objectives
The aim of this course is to teach an object oriented programming overview and
specially getting expertise in vb.net application programming. In this course students learn
basics of vb.net GUI programming, which includes several built-in classes like buttons, text
fields etc. After completing this course the students become able to understand the object
oriented aspects of this language.

Week-1
-Visual Programming: Unlike textual programming, where the program is composed of text
only, visual programming uses visual expressions, spatial arrangements of graphical objects
like arrows, icons, buttons, and other objects to specify program’s semantics. Such a
programming language is called Visual Programming Language (VPL) for example
AgentSheets, Game Maker, LabVIEW, OpenDX, WireFusion.

-Visual Programming Environment (VPE): An environment which assists in generating


code with the help of visual expressions. Such VPEs provide a middle ground between VPLs
and the textual languages. For example Microsoft Visual Studio is a VPE for generating
textual programs in Visual Basic, Visual C#, Visual J#.

-Introduction to Dot Net: .NET is Microsoft's platform for developing and deploying web-
based and windows-based applications. Some of the main goals of .NET are building
applications for different physical and conceptual architectures, multilanguage support and
adaptation of open standards like XML, SOAP, to integrate disparate systems.

-Evolution of Dot Net Framework: MS DOS came out in 1981


A GUI Windows 3.1 (16-bit)
The first release of Win32 was Windows 95. (32-bit)
Windows 98 added more features to support www
ActiveX is a framework for defining reusable software components introduced in 1996 as a
development of COM and OLE technologies.
Dot Net (.NET) [2002]

-Architecture of Dot Net Framework:


.NET Framework is a software framework developed by Microsoft. It includes a library of
classes and interfaces (Framework Class Library (FCL)) and Common Language Runtime
(CLR).

Fall semester 2012 Page 1 of 36


The .NET Framework is an application development platform that provides services for
building, deploying, and running desktop, web, and phone applications and web services. It
consists of the common language runtime (CLR), which provides memory management and
other system services, and an extensive class library, which includes tested, reusable code for
all major areas of application development. (source: https://msdn.microsoft.com/en-
us/library/w0x726c2(v=vs.100).aspx)

The .NET Framework provides the following services for application developers:
 Memory management. In many programming languages, programmers are responsible for
allocating and releasing memory and for handling object lifetimes. In .NET Framework
applications, the CLR provides these services on behalf of the application.
 A common type system. In traditional programming languages, basic types are defined by the
compiler, which complicates cross-language interoperability. In the .NET Framework, basic
types are defined by the .NET Framework type system and are common to all languages that
target the .NET Framework.
 An extensive class library. Instead of having to write vast amounts of code to handle common
low-level programming operations, programmers can use a readily accessible library of types
and their members from the .NET Framework Class Library.
 Development frameworks and technologies. The .NET Framework includes libraries for specific
areas of application development, such as ASP.NET for web applications, ADO.NET for data
access, and Windows Communication Foundation for service-oriented applications.
 Language interoperability. Language compilers that target the .NET Framework emit an
intermediate code named Common Intermediate Language (CIL), which, in turn, is compiled at
run time by the common language runtime. With this feature, routines written in one language
are accessible to other languages, and programmers can focus on creating applications in their
preferred language or languages.
 Version compatibility. With rare exceptions, applications that are developed by using a
particular version of the .NET Framework can run without modification on a later version.
 Side-by-side execution. The .NET Framework helps resolve version conflicts by allowing
multiple versions of the common language runtime to exist on the same computer. This means
that multiple versions of applications can also coexist, and that an application can run on the
version of the .NET Framework with which it was built.
 Multitargeting. By targeting the .NET Framework Portable Class Library, developers can create
assemblies that work on multiple .NET Framework platforms, such as the .NET Framework,
Silverlight, Windows Phone 7, or Xbox 360.
(Source: https://msdn.microsoft.com/en-us/library/w0x726c2(v=vs.100).aspx)

-Framework Class Library (FCL): A collection of classes and interfaces. These classes and
interfaces are divided into namespaces. For example Data namespace contains classes related
to databases:
System.Data, System.Data.Common, System.SQLClient
Some other namespaces: System.Net, System.Reflection, System.Security, System.Threading,
System.Web, System.Xml etc.

-Base Class Library (BCL): It provides fundamental functionality and is the core of FCL.
These classes can be accessed from any .NET language such as VB.NET, C#.NET and they
provide a set of common interfaces. Classes in BCL are divided into namespaces (which is a
fundamental unit of logical code grouping) based on the functionality they provide. These
namespaces are included in BCL: System, System.Text, System.Collections, System.IO,
System.CodeDom, System.Globalization, System.Resources, System.Diagnostics

Fall semester 2012 Page 2 of 36


-Common Language Runtime (CLR): To achieve cross-platform portability .NET
programs are executed in a software environment called Common Language Runtime which
acts as an application virtual machine. It provides different services like memory
management, security, and exception handling. In order for the CLR to provide these services,
managed code includes information called Metadata.
When .NET programs are compiled, they produce MSIL (Microsoft Intermediate Language)
code, instead of machine specific code. This MSIL executes inside the framework and is
known as managed code. Once MSIL is generated it can be executed on different platforms, if
they have their CPU-specific compilers. Whenever resources are used from the application a,
process called Just-in-Time (JIT) compilation occurs which only compiles those parts that
are needed and generates native code and executes them. Fig. 1 depicts this flow.

-Common Language Specification (CLS): It is a set of rules that defines how a language
can be consumed by the CLR. Any third party language that follows these specifications is
supported by CLR. This is how .NET provides multilingual supports.

-Common Type System (CTS): CTS defines what types are allowed to run inside the
framework. A type can be defined as a value type or a reference type.

Contains
MSIL,
Compiled metadata
with
respective
CLR
compiler

.net source .net PE Class Verifier JIT Native


code (vb, c#) .exe/.dll loader code

Assembly JIT compilers

Fig. 1

.net assembly contains CLR header, Metadata, MSIL and native code. CLR header loads the
correct version of CLR. Metadata describes the types used. MSIL is the CPU-independent
code. It also has a small portion of native code, which is directly executed by OS. Native
method Main() called as “unmanaged stub” acts as an entry point. It calls _CorExeMain
function in MSCoree.dll for initializing CLR and hands over the Program Executable (PE) -
.exe or .dll, to CLR. JIT in mscorjit.dll jits the IL to native code.

-History of Visual Basic:

-Introduction to Vb.Net:
VB .NET is a fully object-oriented language, providing inheritance, polymorphism,
encapsulation, overloading, and overriding. With structured exception handling, there is a
clean and consistent method of handling errors not only within a method, but also in a calling
chain of multiple methods, and even across components written in other languages.

-Different Versions of Dot Net Framework and Visual Studio:

Fall semester 2012 Page 3 of 36


Professional Edition: For building internet and desktop application quickly. It offers a
development tool for creating various types of applications like ASP.NET Web applications,
Windows Form based applications, Console applications, Web Services etc.

Enterprise Developer Edition: It contains all the features of Professional edition plus some
other features for enterprise development such as built-in project templates, third party tool
integration, collaborative team development.

Enterprise Architect Edition: It includes all the features of Enterprise Developer edition and
some more features like capabilities for designing, specifying, and communicating application
architecture and functionality. It supports UML and has Visual designer for XML Web
services.

Compact Framework: .NET compact framework is a subset of .NET framework and is


targeted at mobile devices having some client side resources.

Mobile Internet Toolkit: It is designed to develop server side applications for mobile devices
such as cell phones, PDAs, and pagers. It is different than .NET compact Framework in that it
is a server side technology. It is ideal for devices that can not run stand alone applications.

-Introduction to VB.Net IDE:

Week-2

Microsoft Intermediate Language (MSIL): Languages targeting CLR compile to an


intermediate code, called MSIL, instead of CPU-specific native code. IL is an object oriented
assembly language which is entirely stack-based as opposed to CPU-specific assembly
languages which are based on registers.

Just-in-Time (JIT) compilation: Input to JIT is an assembly and its output is a CPU-specific
code, which the target machine can execute. In JIT compilation only those parts of the code
are compiled to processor-specific codes which are invoked for the first time during
execution. For example, if a method is invoked for a second time then a native code produced
on the first call will be used, instead of recompiling the code.

.NET Assembly: A .NET assembly provides a fundamental unit to physical code grouping.
DLL and EXE are assemblies. Our source code is compiled to .exe or .dll which contains the
IL, metadata and manifest. Assemblies are not CPU-specific, therefore when they are about to
execute, the JIT converts them to the target machine native code.

Assembly manifest: Assemblies contain a manifest, which is Metadata that is "emitted" to


the callers of the assembly. The Metadata contains the name of the assembly, the version, the
culture, and optionally the public key for the assembly. Other information in the assembly
includes what types are exported, what types are referenced, and the security permissions for
each type. The MSIL and metadata are contained in a portable executable (PE) file that is
based on and that extends the published Microsoft PE and common object file format (COFF)
used historically for executable content. It can be stored with MSIL in the PE or in a separate
file.

Fall semester 2012 Page 4 of 36


.NET Namespace: A .NET namespace provides a fundamental unit of logical code grouping.
We use dot separated hierarchies of classes to include specific classes from the library.

Intermediate Language Assembler (ILASM): It is a repacking tool. It takes IL code and


packages the code into a file in the PE format.

Intermediate Language Disassembler (ILDASM): It can be used to disassemble an


assembly to IL. For example to generate IL from abc.exe we run this command from
command prompt: Ildasm.exe abc.exe /out:abc.il

-Code Compilation and Execution Steps:


1- Writing the source code: Use MS Visual Studio to write and edit your code
2- Compiling the source code to MSIL: The compiler translates source code into MSIL
(which is a CPU-independent set of instructions). CLR supplies JIT compilers for each
architecture it supports, therefore MSIL can be JIT-compiled and run on any supported
architecture.
3- Compiling MSIL to Native code: MSIL is not an executable code, therefore it must be
compiled against the CLR to native code for the target machine architecture.
One way to do this is by using JIT compiler. During this compilation the MSIL is verified to
be type safe.
Ahead-of-time compilation can also be done for MSIL. In this case the conversion from IL to
native code takes place before running the application and the entire assembly is converted.
The generated native code persists as a file on disk.

-Overview of Console and Windows Applications: Console applications are non-GUI


applications based on characters and are referred to as Character User Interface (CUI).
Windows applications are based on Graphical User Interface (GUI).

-Getting Started with Console Application:


-Data Types: The .NET type system has two different kinds of types namely Value types and
Reference types. Value types directly contain the data, and instances of value types are either
allocated on the stack or allocated inline in a structure. Value types can be built-in
(implemented by the runtime), user-defined, or enumerations.
Every type in .NET (including types like Integer, Double or other classes) is derived from the
Object class.
The core value types supported by the .NET platform reside within the root of the
System namespace. These types are often referred to as the .NET “Primitive Types”.
Using reference types for primitive data like integers, characters, and decimals will introduce
the overhead of heap allocation and the constructor calling convention. Therefore .NET uses
value types i-e structures for such data. Value types remain lightweight as they do not carry
Run Time Type Information (RTTI). RTTI is a mechanism that allows the type of an object to
be determined during program execution.
Value types are literally types subclassed from the System.ValueType class. Types derived
from ValueType are structures. A structure is a value type that derives implicitly from
ValueType, which in turn is derived from Object.
When we request type information for a value type, like Integer, .NET boxes the value type
for example:
Dim i As Integer = 5
Console.WriteLine(i.GetType())

Fall semester 2012 Page 5 of 36


Reference types store a reference to the value's memory address, and are allocated on the
heap. Reference types can be self-describing types, pointer types, or interface types. The type
of a reference type can be determined from values of self-describing types. Self-describing
types are further split into arrays and class types.

Differences between value type and reference type:


-Garbage collector collects the unreferenced instances of reference type. Value types are
automatically cleaned up when the variable goes out of scope.
-Copying a reference type to another reference type of the same type copies only the reference
(shallow copy), while in case of value type the content is copied (deep copy).
-Two reference types are determined to be equal if they both have the same reference. Two
value types are equal if their contents are equal.
-A reference type is initialized to NULL but a value type contains a valid type.

The following programs show that copying one value type to another value type copies the
contents, while for reference type the reference is copied.

Public Class Class1


Private RollNum As Integer
Public Property RollNumber() As Integer
Set(ByVal Value As Integer)
RollNum = Value
End Set
Get
Return RollNum
End Get
End Property
End Class

Public Module Module1


Public Structure ValueTypeTest
Public val1 As Integer
End Structure
Sub Main()
Dim c1 As Class1
Dim c2 As Class1
c1 = New Class1()
c2 = New Class1()
c1.RollNumber = 4
c2 = c1
c2.RollNumber = 7
Console.WriteLine("c1.rollNum = {0}, c2.rollNum = {1}",
c1.RollNumber, c2.RollNumber)

Dim struct1 As ValueTypeTest


Dim struct2 As ValueTypeTest
struct1.val1 = 4
struct2 = struct1
struct2.val1 = 7
Console.WriteLine("struct1.val1 = {0}, struct2.val1 = {1}",
struct1.val1, struct2.val1)
Console.ReadKey()
End Sub
End Module

Output: c1.rollNum = 7, c2.rollNum = 7


struct1.val1 = 4, struct2.val1 = 7
In VB .NET, all data types allowed are CLS–compliant. In the .NET Framework, all data
types are derived from the System namespace. Because all objects in .NET are derived from

Fall semester 2012 Page 6 of 36


the base type System.Object, the data types you are using are actually classes and structures
derived from the System.Object type. All classes have members, properties, and fields; the
data types defined in the System namespace are no different.

Type Size in bytes Range


Boolean 4 True or False
Byte 1 0 to 255 unsigned
Char 2 0 to 65,535 unsigned
Date 8 January 1, 1 to December 31, 9999
Double 8 1.797693134862231E308 to –4.94065645841247 for
negative values
4.94065645841247 to 1.797693134862231E308 for
positive values
Integer (CLS: 4 –2,147,483,648 to 2,147,483,647
System.Int32)
Long (CLS: 8 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
System.Int64)
Short (CLS: 2 –32,768 to 32,767
System.Int16)
Single 4 1.5 x 10-45 to 3.4 x 1038 (Precision: 7 digits)
5.0 x 10-324 to 1.7 x 10 308 (Precision: 15 digits)
Double 8
-28
1.0 x 10 to 7.9 x 10 28 (Precision: 28 digits)
Decimal 16
String maximum length of 2,147,483,647 characters.

-Module: Modules are created with a keyword Module but actually they are special classes.
The compiler generates a NotInheritable (sealed) class i-e we cannot instantiate an object of a
module. A module is implicitly imported into every source file in a project, so the methods
and properties of the module can be accessed without being fully qualified. Procedures
defined inside a module are globally accessible in the current namespace.
‘Module‘statement can occur only at file or namespace level.
If your project’s Main sub is not included in a Module then you have to change Startup Object
to Sub Main instead of Module in the project properties.

-Declaring Variables: General syntax:


[ Dim | Public | Protected | Friend | Protected Friend | Private | Static ]
variablename As [ New ] type = [expression]

Dim and Private are both considered Private. The Dim (for Dimension) keyword is
allowed within a procedure block. Public, Private, Shared, and Friend are not
allowed when declaring variables within a procedure block.
Dim age As Integer
We can also initialize it at the time of declaration as:
Dim age As Integer = 20

Private percentage As Single

Dim d1 As Date = "7-15-2017" 'stored as MM/dd/yyyy


Console.WriteLine("d1 = {0}", d1.ToString("dd/MM/yyyy")) 'to print as
dd/MM/yyyy

-Declaring Constants: We need to specify the value of the constant when we declare it.

Fall semester 2012 Page 7 of 36


Const age As Integer = 10

-Type conversion: We can use built-in functions to convert from one type to another. But the
compiler can also do some automatic conversions.
Widening: When the target type is larger in size then the original data value is maintained
without data loss.
Dim intValue As Integer = 1234
Dim singleValue As Single
singleValue = intValue

Narrowing: Conversion attempts to convert data from a larger type to a smaller type (in bytes
or precision) that may not be able to maintain the original value.
Dim singleValue As Single = 4.59
Dim intValue As Integer
intValue = singleValue

-Built-in functions for explicit type conversion (left over from VB):
CBool, CByte, CChar, CDate, CDbl, CDec, CInt, CLng, CObj, CShort, CSng,
CStr and CType.
Dim doubValue As Double = 6.95
Dim intValue As Integer = CInt(doubValue)

If data is lost in a conversion then a runtime error is generated.


Dim longValue As Long = 234985
Console.WriteLine(CShort(longValue))

System.Convert: The System.Convert class supports similar functionality of the built-in


conversion functions of VB .NET.
Dim longValue As Long = 327
Dim intValue As Integer = Convert.ToInt32(longValue)

-Boxing: Boxing is the implicit conversion of a value type to a reference type. When boxing
occurs, the contents of value type are copied from the stack into the memory allocated on the
managed heap.

Dim valueType As Integer = 10


Dim objType As Object
objType = valueType 'boxing

-UnBoxing: UnBoxing is the explicit conversion from a reference type to a value type. When
unboxing occurs, memory is copied from the managed heap to the stack. For an unboxing
conversion to a given value type to succeed at run time, the value of the source argument
must be a reference to an object that was previously created by boxing a value of that type,
otherwise an exception is thrown.

valueType = objType 'unboxing ok

Dim obj2 As New Object


valueType = obj2 'throws exception because obj2 was not previously created
by boxing a value

Exception:
An unhandled exception of type 'System.InvalidCastException' occurred in
Microsoft.VisualBasic.dll

Additional information: Conversion from type 'Object' to type 'Integer' is


not valid.

Fall semester 2012 Page 8 of 36


-Working with Option Explicit and Option Strict: When Option Explicit is ON we cannot
use a variable before declaring it. When Option Strict is ON then no implicit type narrowing
conversion will take place and the program will not compile until we do the conversion
explicitly.

Option Explicit Off


Option Strict On

-Working with Global Variables: Variables declared in a module outside functions and sub
procedures are accessible from anywhere in the module. If there is a local variable with the
same name as a global variable then the local will override, inside the local scope, the global
one.

Public Module Module1


Dim globVar As Integer
Sub Main()
globVar = 10
Console.WriteLine("globVar = {0}", globVar)
funct()
Console.WriteLine("globVar = {0}", globVar)
Console.ReadKey()
End Sub
Function funct() As Integer
'Dim globVar As Integer 'uncomment this line to see how local hides
global
globVar = 20
funct = globVar
End Function
End Module

-CLS compliant code: Code that follows CLS rules and restrictions.
If you want your code to be CLS-compliant, you must expose functionality in a way that is CLS-
compliant in the following places:
 Definitions of your public classes.
 Definitions of the public members of public classes, and of members accessible to derived
classes (family access).
 Parameters and return types of public methods of public classes, and of methods accessible to
derived classes.
The features you use in the definitions of your private classes, in the definitions of private methods on
public classes, and in local variables do not have to follow the CLS rules.
(source: https://msdn.microsoft.com/en-us/library/bhc3fa7f.aspx)

In order to enable warnings for CLS non-compliant code, include CLSCompliant(True).


<Assembly: CLSCompliant(True)>
Public Class Multilang
Public Sub ChangeValue(ByVal value As UInteger)
End Sub
End Class

UInteger is CLS non-compliant, therefore it will show warning.

We can also mark a class or a procedure as CLS compliant or non-compliant.


<CLSCompliant(True)> Public Class Multilang
<CLSCompliant(True)> Public Sub NotCompPro(ByVal value As UInteger)
End Sub
End Class

Fall semester 2012 Page 9 of 36


-Cross language access: The following example shows how .net CLS provides support for
multi-language programming. Save the following ClassLibrary1 as a C# class library (.dll)
project.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

[assembly: CLSCompliant(true)]

[CLSCompliant(true)]
public class ClassLibrary1
{
public string name;

public ClassLibrary1()
{
name = "unknown";
}

public void SetName(string newName)


{
name = newName;
}

public string GetName()


{
return name;
}
}

The following VB.net code is using the above C# class to call SetName() and GetName()
methods. But to use the C# class library ClassLibrary1 we need to add a reference to it in the
vb.net project.
Option Explicit On
<Assembly: CLSCompliant(True)>

Public Class Multilang


Public Shared Sub Main()
Dim c1 As New ClassLibrary1
c1.SetName("Jamal")
Console.WriteLine(c1.GetName())
Console.ReadKey()
End Sub
End Class

Week-3
-Variable scope: The scope of a variable can be declared as Private, Public, Static, Shared,
Protected, or Friend.

Public variables are available to all procedures in all classes, modules, and structures.
Public Module MainModule
Public Class Class1
Public pubVar As Integer = 123
Sub printPubVar()
Console.WriteLine("pubVar = {0}", pubVar)
End Sub
End Class
Sub Main()
Dim obj1 As Class1 = New Class1()

Fall semester 2012 Page 10 of 36


Console.WriteLine("pubVar = {0}", obj1.pubVar)
Console.ReadKey()
End Sub
End Module

Static variables retain their values until the values of the variables are reset, or until the
application ends.
Public Module Module1
Sub Sub1()
Static staticVar As Integer = 123
staticVar = staticVar + 1
Console.WriteLine("staticVar = {0}", staticVar)
End Sub

Sub Main()
Sub1()
Sub1()
Console.ReadKey()
End Sub
End Module

Shared variables: Shared members are properties, procedures, or fields that are shared by all
instances of a class.

Module MainModule
Public Class Count
Private Shared objCount As Integer

Sub New()
objCount = objCount + 1
Console.WriteLine("Object {0} created", objCount)
End Sub
End Class
Sub Main()
Dim count1 As Count = New Count
Dim count2 As Count = New Count
Console.ReadKey()
End Sub
End Module

Output: Object 1 created


Object 2 created
But if we remove the shared key word from the variable objCount then the output will be
Object 1 created
Object 1 created
because the variable is no more shared by the objects.

We cannot call a non-shared procedure from a shared procedure as the following example
shows. Also note that for the program to start execution from the Main() of the class the
Main() should be Shared.

Public Class Count


Private Sub WelcomeMsg()
Console.WriteLine("Welcome to VB.net")
End Sub

Shared Sub Main()


Dim count1 As Count = New Count
'WelcomeMsg() 'cannot refer to an instance member of a class from
within a shared procedure

Fall semester 2012 Page 11 of 36


count1.WelcomeMsg()
Console.ReadKey()
End Sub
End Class

Private variables are accessible only in the module, class, or structure in which they are
declared. Private and Dim are the same except that Private cannot be used to declare
variables within a function or subprocedure.

Public Class Count


Private PriVariable As Char
End Class

Public Class MainClass


Shared Sub Main()
Dim count1 As New Count
Console.WriteLine(count1.PriVariable) 'not accessible
Console.ReadKey()
End Sub
End Class

-Arrays: Array is a set of values of the same type, for example roll numbers of the students in
a class.

Array declaration:
Dim rollNo(9) As Integer
The above statement will create an array with 10 elements. The indexing will start from 0.

Declaration and initialization:


Dim rollNo = New Integer() {10, 11, 12, 13, 14}
For i As Integer = 0 To rollNo.Length - 1
Console.WriteLine(rollNo(i))
Next

The size of an existing array can be redefined while retaining the current values as:
Dim rollNo = New Integer() {10, 11, 12, 13, 14}
ReDim Preserve rollNo(19)
For i As Integer = 0 To rollNo.Length - 1
Console.WriteLine(rollNo(i))
Next

The above code snippet will print the 5 roll numbers and 15 zeros. The elements are
initialized to 0 by default. If the Preserve keyword is removed then the previous values will
be lost.

Declaration a two-dimensional array:


Dim grades(3, 3) As Char

Declaration and initialization a two-dimensional array:


Module Module1
Sub Main()
Dim grades = New Char(2, 2) {{"A", "B", "C"}, {"D", "E", "F"},
{"G", "H", "I"}}

For i As Integer = 0 To grades.GetUpperBound(0)


For j As Integer = 0 To grades.GetUpperBound(1)
Console.Write(grades(i, j) & " ")
Next
Console.WriteLine()

Fall semester 2012 Page 12 of 36


Next
Console.ReadLine()
End Sub
End Module

Output:
A B C
D E F
G H I

-Structures:
Structure is a container type, which can contain other types. Unlike an array, which can hold
data of only one type, a structure can contain data of different types. For example to store
information of a student such as rollno (Integer), name (String), gpa (Single) we can define a
structure.

General syntax:
[{Public | Private}] Structure structure_name
Variable declaration
[procedure declaration]
End Structure

In the members variables are declared with Dim keyword then they are publicly accessible.

Example1:
Module Module1
Sub Main()
Dim s1 As Student
s1.rollNo = 123
s1.gpa = 3.2
Console.WriteLine("rollno GPA")
Console.WriteLine("{0} {1}", s1.rollNo, s1.gpa)
Console.ReadLine()
End Sub
End Module

Structure Student
Dim rollNo As Integer
Dim gpa As Single
End Structure

Output:
rollno GPA
123 3.2

Example2:
Module Module1
Sub Main()
Dim studs(0) As Student
Dim sno As Integer = 0
Console.WriteLine("Enter number of students:")
sno = Console.ReadLine()
ReDim studs(sno)
Dim st As Student
For i As Integer = 0 To sno - 1
Console.WriteLine("Enter rollno for stud {0}", i + 1)
st.rollNo = Console.ReadLine()
Console.WriteLine("Enter subject1 marks for stud {0}", i + 1)
st.subj1 = Console.ReadLine()

Fall semester 2012 Page 13 of 36


Console.WriteLine("Enter subject2 marks for stud {0}", i + 1)
st.subj2 = Console.ReadLine()
studs(i) = st
Next
Console.WriteLine("rollno subj1 subj2 per")

For i As Integer = 0 To sno - 1


studs(i).perc = (studs(i).subj1 + studs(i).subj2) / 2
Console.WriteLine("{0} {1} {2} {3}", _
studs(i).rollNo, studs(i).subj1,
studs(i).subj2, studs(i).perc)
Next
Console.ReadLine()
End Sub
End Module

Structure Student
Dim rollNo As Integer
Dim subj1, subj2 As Integer
Dim perc As Single
End Structure

Output:
Enter number of students:
3
Enter rollno for stud 1
10
Enter subject1 marks for stud 1
56
Enter subject2 marks for stud 1
60
Enter rollno for stud 2
11
Enter subject1 marks for stud 2
80
Enter subject2 marks for stud 2
70
Enter rollno for stud 3
12
Enter subject1 marks for stud 3
67
Enter subject2 marks for stud 3
57

rollno subj1 subj2 per


10 56 60 58
11 80 70 75
12 67 57 62

-Operators:
-Arithmetic (+, -, *, /, %, ^)
-Concatenation (&): To concatenate the operands. + can also be used for concatenation, but
when to avoid confusion in case of some operands, it is preferred to us & when concatenation
in intended.

Dim s As String
s = "Welcome"

Fall semester 2012 Page 14 of 36


s = s & " to VB.ent"

Console.WriteLine("3" + "5") 'output:35


Console.WriteLine("3" + 5) 'output:8 because of implicit conversion
Console.WriteLine("3" & "5") 'output:35
Console.WriteLine("abc" + 5) 'output:error (conversion from string to
integer failed)

Console.WriteLine(10 Mod 3) 'output:1 (the remainder when 10 is divided by


3)
Console.WriteLine(3 Mod 10) 'output:3

-Relational operators (>, <, >=, <=, =, <>): These operators takes two operands and the
results is either True of False.

> for greater than


< less than
>= greater than or equal to
<= less than or equal to
= equal to (note that instead of == , as was the case in C++ or JAVA, here only one = is used
for comparison)
<> not equal to

-Logical operators: And, Or, Not


The results of these operations are either True of False. ‘Not’ is a uniary operator.

Week-4

-Conditions:
-If then else statement:
Dim marks As Integer = 50
If (marks <= 49) Then
Console.WriteLine("Fail")
Else
Console.WriteLine("Pass")
End If

-Elseif:
Dim marks As Integer = 70
If (marks <= 49) Then
Console.WriteLine("Fail")
ElseIf (marks >= 50 And marks <= 69) Then
Console.WriteLine("C")
ElseIf (marks >= 70 And marks <= 80) Then
Console.WriteLine("B")
Else
Console.WriteLine("A")
End If
-Select… end select statement: Its function is almost the same as if-then-else but it cannot
evaluate more than one expression. If-then-else can be used to test multiple alternative Boolean
expressions in each block of the entire construct. Select Case examines only one expression and uses
the result to select the case for true condition.
Select-case is more suitable if there are many options to select from.

Dim day As Integer = 3


Select Case day
Case 1
Console.WriteLine("Monday")
Case 2

Fall semester 2012 Page 15 of 36


Console.WriteLine("Tuesday")
Case Else
Console.WriteLine("Friday")
End Select

Case Else is optional.

Dim age As Integer = 19


Select Case age
Case Is <= 0
Console.WriteLine("Invalid")
Case Is <= 20
Console.WriteLine("Less than 20")
Case Else
Console.WriteLine("More than 20")
End Select

Dim age As Integer = 25


Select Case age
Case 0 To 0
Console.WriteLine("Invalid")
Case 13 To 19
Console.WriteLine("Teenager")
Case Else
Console.WriteLine("More than 19")
End Select

Dim month As Integer = 6


Select Case month
Case 1, 3, 5, 7, 8, 10, 12
Console.WriteLine("31 days")
Case 2, 4, 6, 9, 11
Console.WriteLine("30 days")
Case Else
Console.WriteLine("29")
End Select

-Loops: Loops are used for repeating a statement or a set of statements multiple times
without writing the statement(s) multiple times.

-Do While: The While loops are usually used in cases where it is not known in advance that
how many times the body of the loop should execute. E.g. repeating the body of the loop until
the user enters a specific character.
Example:
Module Module1
Sub Main()
Dim cond As Char = "y"
Do While cond = "y"
'perform some task here
Console.WriteLine("Do you want to continue (y/n)")
cond = Console.ReadLine()
Loop
End Sub
End Module

Example:
Dim counter As Integer = 0
Do While counter <= 10 'execute the body until the condition becomes false
Console.WriteLine("Line {0}", counter)
counter = counter + 1
Loop

Fall semester 2012 Page 16 of 36


Example:
Dim counter As Integer = 0
Do Until counter > 10 'execute the body until the condition becomes true
Console.WriteLine("Line {0}", counter)
counter = counter + 1
Loop

-Premature exit from a loop: To exit/terminate a do while loop before the initial set
condition we use Exit Do

Dim counter As Integer = 0


Do While counter <= 10 'execute the body until the condition becomes false
Console.WriteLine("Line {0}", counter)
counter = counter + 1
If (counter = 5) Then
Exit Do
End If
Loop

The test condition can also be put at the end of the Do while/until loop in which case the body
of the loop will get executed at least once even though the condition might not be true before
executing the loop.

Do
Loop While counter <= 10 'execute the body until the condition becomes false

Do Until counter > 10 'execute the body until the condition becomes true
Loop

-While End While: Repeats the body of the loop until the condition becomes false. For
premature exit use Exit While

Dim counter As Integer = 0


While counter <= 10 'execute the body until the condition becomes false
Console.WriteLine("Line {0}", counter)
counter = counter + 1
If (counter = 5) Then
Exit While
End If
End While

-For Next: General structure is given below. Bracketed terms are optional:
For Counter = <StartValue> To <EndValue> [Step] [StepValue]
[Statement(s)]
[Exit For]
Next [Counter]

By default the step value is 1

For counter = 1 To 10 Step 1


Console.WriteLine("Line {0}", counter)
If (counter > 5) Then
Exit For
End If
Next counter

-For Each: General structure is given below. Set is a collection like an array.
For Each i In Set

Fall semester 2012 Page 17 of 36


[Statement(s)]
[Exit For]
Next [Counter]

Dim Marks() As Double = {23.5, 78.2, 80.7}


For Each i In Marks
Console.WriteLine(i)
Next i

Another example:
Public Class Student
Private StudName As String
Private StudRollNo As Integer

Public Property StudentName() As String


Set(ByVal Value As String)
StudName = Value
End Set
Get
Return StudName
End Get
End Property

Public Property StudentRoll() As Integer


Set(ByVal Value As Integer)
StudRollNo = Value
End Set
Get
Return StudRollNo
End Get
End Property
End Class

Public Class StudentDemo


Shared Sub Main()
Dim Stud1 As New Student
Dim Stud2 As New Student
Dim Stud3 As New Student
Stud1.StudentName = "Akmal"
Stud2.StudentName = "Shafiq"
Stud3.StudentName = "Zahra"
Stud1.StudentRoll = 102
Stud2.StudentRoll = 103
Stud3.StudentRoll = 104

Dim Students() As Student = {Stud1, Stud2, Stud3}


For Each Stud In Students
Console.WriteLine("Name: {0}, Roll Number {1}",
Stud.StudentName, Stud.StudentRoll)
Next Stud

Console.ReadKey()
End Sub
End Class

-Nesting loops: One loop can be nested in another.


Example:
For i As Integer = 1 To 5
For j As Integer = 1 To 4
Console.Write("*" & " ")
Next
Console.WriteLine() 'this is for newline
Next
Output:
****

Fall semester 2012 Page 18 of 36


****
****
****
****
In the above example the outer loop is controlling the number of times the four stars should
print, which in this example are set to 5. The inner loop controls the number of stars to print,
which in this example are set to 4.

Week-5
-Working with string
String is a reference type defined by System.String class. It is immutable, i-e once its object is
created it cannot be modified. Modifying a string (e.g. by concatenation) will result in a new
string object.

Dim str As String = "Welcome"


str = String.Concat(str, " to Peshawar")

The second statement creates a new string object with value “Welcome to Peshawar” and
assigs it to the reference str.

ToUpper: Changes all the characters of a string to upper case.


Dim str As String = "welcome"
Console.WriteLine(str.ToUpper) 'WELCOME

ToLower: Changes all the characters of a string to lower case.

Replace: Replaces all occurrence of a character in the string with another character.
Dim str As String = "This is a sample string."
Console.WriteLine(str.Replace("i", "I"))

Trim: Remove any leading and trailing white-spaces from the string.
Dim str As String = " This is a sample string. "
Console.WriteLine("length of str before triming {0}", str.Length)
str = str.Trim()
Console.WriteLine("length of str after triming {0}", str.Length)

Output:
length of str before triming 32
length of str after triming 24

Overloaded form: removing leading and trailing characters specified by a char array.
Dim str As String = "***+**This is a sample string.+**+*"
Dim totrim As Char() = {"*"c, "+"c}
Console.WriteLine(str.Trim(totrim))

Output:
This is a sample string.

Length: Returns an integer representing the number of characters in the string


Dim str As String = "Visual Programming"
Console.WriteLine(str.Length) ' output: 18

Reverse: Reverses the order of characters in a string and returns a collection of chars.
Dim str As String = "Visual Programming"

Fall semester 2012 Page 19 of 36


Dim h As IEnumerable = str.Reverse()
For Each i In h
Console.Write(i)
Next

Output:
gnimmargorP lausiV

As the Reverse function returns an IEnumerable collection therefore to print the reversed
string we can use a For Each loop.

Splits: Splits a string by a specified character and returns an array of substrings.


Dim str As String = "This is a sample string."
For Each i In str.Split(" ")
Console.WriteLine(i)
Next

The above example splits the string by the space character.


Output:
This
is
a
sample
string.

Join: Joins an array of string into one string separated by the specified char.
Dim str As String() = {"This", "is", "a", "sample", "string."}
Console.WriteLine(String.Join(" ", str))

Output:
This is a sample string.

Compare: Compares two strings and returns an integer to indicate their relative position in
the sort order. If the returned value is:

less than 0: str1 comes before str2 in the sort order (e.g. Compare(A, B) returns -1)
zero: str1 and str2 are at the same position in sort order (e.g. Compare(A, A) returns 0)
greater than zero: st1 comes after str2 in the sort order. (e.g. Compare(B, A) returns 1)

Ordinal: 0, 9, a, A

Dim str1 As String = "Abc"


Dim str2 As String = "Abc"
Console.WriteLine(String.Compare(str1, str2))
The above statements will return 0 showing that the two strings are at the same position in the
sort order.

The below code also return 0, because the comparison is case-insensitive as the third
argument is set to True.
Dim str1 As String = "abc"
Dim str2 As String = "Abc"
Console.WriteLine(String.Compare(str1, str2, True))

But this code returns -1, because the comparison is now case-sensitive as the third argument
is set to False.

Fall semester 2012 Page 20 of 36


Dim str1 As String = "abc"
Dim str2 As String = "Abc"
Console.WriteLine(String.Compare(str1, str2, False))

Equals: To test if two strings are equal.


String.Equals("alpha", "Alpha") ' returns: False

To ignore case use StringComparison.OrdinalIgnoreCase i-e. use Order but Ignore Case.
Console.WriteLine(String.Equals("alpha", "Alpha",
StringComparison.OrdinalIgnoreCase)) ' returns: True

Concate: Concatenates multiple strings into one string.


Dim str1 As String = "Visual "
Dim str2 As String = "Programming"
Console.WriteLine(String.Concat(str1, str2))

Output: Visual Programming


IndexOf: Returns the index of the first occurrence of the specified character in a string.
Dim str As String = "This is a long string "
Console.WriteLine(str.IndexOf("a"))
These statements returns 8.

LastIndexOf: Returns the index of the last occurrence of the specified character in a string.

Substring: Returns a substring from a string.


Dim str As String = "This is a long string "
Console.WriteLine(str.Substring(10)) ' returns: long string
Console.WriteLine(str.Substring(10, 4)) ' returns: long

The argument 10 in the first Substring call represents the starting index of the substring and
goes till the end of the string.
In the second statement the substring starts from 10 and the length goes to 4 characters.

Remove: Removes a specified number of characters from a string.


Dim str As String = "This is a long string "
Console.WriteLine(str.Remove(10, 5)) ' output: This is a string

Week-6
-Advantages of procedures: Procedures allow logical grouping of code into tasks and makes
program more readable. Procedures perform a specific task and can be called multiple times,
which helps in avoiding repetition of code.

-Types of procedures: There are three main types of procedures: i) Sub Procedure, ii)
Function procedure, and iii) Property procedure

-Sub Procedures: They perform a specific task but do not return a value to the caller.
General syntax:
[ <attrlist> ] [{ Overloads | Overrides | Overridable |NotOverridable | MustOverride | Shadows | Shared}]
[{ Public | Protected | Friend | Protected Friend | Private}]
Sub name [(arglist)]
[ statements ]
[ Exit Sub ]
[ statements ]
End Sub

Fall semester 2012 Page 21 of 36


<CLSCompliant(True)>
Public Class ProcedureDemo
<CLSCompliant(True)> Public Shared Sub Sum(ByVal Number1 As Integer,
ByVal Number2 As Integer)
Console.WriteLine("Sum of {0} and {1} is {2}", Number1, Number2,
Number1 + Number2)
End Sub
Shared Sub Main()
Sum(2, 5)
Console.ReadKey()
End Sub
End Class

We can also call the above procedure as:


Call Sum(2, 5)

Parameters can be passed either by value or by reference: ByVal or ByRef

-The Sub Main procedure: Every VB.net program must contain a Sub Main procedure
because the program execution starts from there. Its general structure is:
Sub Main()
'Code goes here
End Sub

-Function procedures: They also perform a specific task but they may return a value to the
caller.
<CLSCompliant(True)> Public Shared Function Square(ByVal Num) As Integer
Return Num * Num
'[Exit Function]
End Function

To explicitly exit a function we write: Exit Function


There are two ways to return value from a function. Either use the return statement as done in
the above example or assign the value to the name of the function as shown below:
<CLSCompliant(True)> Public Shared Function Square(ByVal Num) As Integer
Square = Num * Num
End Function

-Property Procedures: Properties are used to get/set fields of a class, structure or module.

Public Class Student


Private StudName As String
Public StudRollNo As Integer
Public Property StudentName() As String
Set(ByVal Value As String)
StudName = Value
End Set
Get
Return StudName
End Get
End Property
End Class
Public Class StudentDemo
Shared Sub Main()
Dim Stud1 As New Student
Stud1.StudentName = "Akmal" ' Private field member StudName is accessed via
property
Stud1.StudRollNo = 312 'StudRollNo is directly accessible as it is public
Console.WriteLine("Name: {0} and Roll Number: {1}", Stud1.StudentName,
Stud1.StudRollNo)

Console.ReadKey()

Fall semester 2012 Page 22 of 36


End Sub
End Class

-Argument passing (Passing by value vs Passing by reference):


When a value type is passed ByVal to a procedure, a new variable is created in the procedure
and gets a copy of the value from the caller. Any changes to the variable in the procedure
does not reflect in the caller.

Example1: Passing value type by value

Module Module1
Sub Main()
Dim v1 As Integer = 1
Dim v2 As Integer = 2
Console.WriteLine("Before calling M1: v1 = {0}, v2 = {1}", v1, v2)
M1(v1, v2)
Console.WriteLine("After calling M1: v1 = {0}, v2 = {1}", v1, v2)
Console.ReadLine()
End Sub

Sub M1(ByVal v1temp As Integer, ByVal v2temp As Integer)


Dim temp As Integer = v1temp
v1temp = v2temp
v2temp = temp
End Sub
End Module

Output:
Before calling M1: v1 = 1, v2 = 2
After calling M1: v1 = 1, v2 = 2

The swaping inside M1 does not affect the variables declared in Sub Main()
1 V2 2
V1 In Sub Main

Value is copied to another memory location

1 V2temp 2
V1temp In M1

Example2: Passing value type by reference

Module Module1
Sub Main()
Dim v1 As Integer = 1
Dim v2 As Integer = 2
Console.WriteLine("Before calling M1: v1 = {0}, v2 = {1}", v1, v2)
M1(v1, v2)
Console.WriteLine("After calling M1: v1 = {0}, v2 = {1}", v1, v2)
Console.ReadLine()
End Sub

Sub M1(ByRef v1temp As Integer, ByRef v2temp As Integer)


Dim temp As Integer = v1temp
v1temp = v2temp
v2temp = temp
End Sub
End Module

Fall semester 2012 Page 23 of 36


Output:
Before calling M1: v1 = 1, v2 = 2
After calling M1: v1 = 2, v2 = 1

The swapping inside M1 also affect the variables declared in Sub Main()
1 V2 2
V1 In Sub Main

V1temp is another name for memory location


V1

V1temp V2temp In M1

Example3: Passing reference type by value

Module Module1
Sub Main()
Dim v1 As New Student
v1.SetRollNo(123)
Dim v2 As New Student
v2.SetRollNo(456)
Console.WriteLine("Before calling M1: v1.RollNo = {0}, v2.RollNo =
{1}", v1.getRollNo, v2.getRollNo)
M1(v1, v2)
Console.WriteLine("After calling M1: v1.RollNo = {0}, v2.RollNo =
{1}", v1.getRollNo, v2.getRollNo)
Console.ReadLine()
End Sub

Sub M1(ByVal v1temp As Student, ByVal v2temp As Student)


v1temp.SetRollNo(124)
v2temp.SetRollNo(457)
End Sub
End Module

Class Student
Private rollNo As Integer
Public Sub SetRollNo(ByVal r As Integer)
rollNo = r
End Sub
Public Function getRollNo() As Integer
Return rollNo
End Function
End Class

Output:
Before calling M1: v1.RollNo = 123, v2.RollNo = 456
After calling M1: v1.RollNo = 124, v2.RollNo = 457

Changing the variables of M1 also affects the variables declared in Sub Main()
RollNo=123 V2 RollNo=456
V1 In Sub Main

As the variables are of Reference type,


therefore their reference are copied by value

V1temp V2temp In M1

Fall semester 2012 Page 24 of 36


Think of this scenario as: V1 and V1temp both contain the same address. Changing the value
through any one of them will be reflected by the other.

Example4: When a reference type is passed by value, and the reference of the variable in the
called procedure is changed, it would not affect the variable in the caller.

Module Module1
Sub Main()
Dim v1 As New Student
v1.SetRollNo(123)
Dim v2 As New Student
v2.SetRollNo(456)
Console.WriteLine("Before calling M1: v1.RollNo = {0}, v2.RollNo =
{1}", v1.getRollNo, v2.getRollNo)
M1(v1, v2)
Console.WriteLine("After calling M1: v1.RollNo = {0}, v2.RollNo =
{1}", v1.getRollNo, v2.getRollNo)
Console.ReadLine()
End Sub

Sub M1(ByVal v1temp As Student, ByVal v2temp As Student)


Dim temp As Student = v1temp
v1temp = v2temp
v2temp = temp
Console.WriteLine("Inside M1: v1temp.RollNo = {0}, v2temp.RollNo =
{1}", v1temp.getRollNo, v2temp.getRollNo)
End Sub
End Module

Class Student
Private rollNo As Integer
Public Sub SetRollNo(ByVal r As Integer)
rollNo = r
End Sub
Public Function getRollNo() As Integer
Return rollNo
End Function
End Class

Output:
Before calling M1: v1.RollNo = 123, v2.RollNo = 456
Inside M1: v1temp.RollNo = 456, v2temp.RollNo = 123
After calling M1: v1.RollNo = 123, v2.RollNo = 456

In the above example when the references are swapped inside M1, they now refer to each
other’s objects, but the actual references in the Sub Main still point to their original objects,
as shown by the output.

RollNo=123 V2 RollNo=456
V1 In Sub Main

As the variables are of Reference type,


therefore their references are copied by value

V1temp V2temp In M1, before swap

V1temp V2temp In M1, after swap


Fall semester 2012 Page 25 of 36
Think of this scenario as: V1 and V1temp both contain the same address. Changing the value
through any one of them will be reflected by the other. Changing the address for any one of
them will not change the address for the other, because the address was copied.

Example5: When a reference type is passed by reference, and the reference of the variable in
the called procedure is changed, it would also affect the variable in the caller.

Module Module1
Sub Main()
Dim v1 As New Student
v1.SetRollNo(123)
Dim v2 As New Student
v2.SetRollNo(456)
Console.WriteLine("Before calling M1: v1.RollNo = {0}, v2.RollNo =
{1}", v1.getRollNo, v2.getRollNo)
M1(v1, v2)
Console.WriteLine("After calling M1: v1.RollNo = {0}, v2.RollNo =
{1}", v1.getRollNo, v2.getRollNo)
Console.ReadLine()
End Sub

Sub M1(ByRef v1temp As Student, ByRef v2temp As Student)


Dim temp As Student = v1temp
v1temp = v2temp
v2temp = temp
Console.WriteLine("Inside M1: v1temp.RollNo = {0}, v2temp.RollNo =
{1}", v1temp.getRollNo, v2temp.getRollNo)
End Sub
End Module

Class Student
Private rollNo As Integer
Public Sub SetRollNo(ByVal r As Integer)
rollNo = r
End Sub
Public Function getRollNo() As Integer
Return rollNo
End Function
End Class

Output:
Before calling M1: v1.RollNo = 123, v2.RollNo = 456
Inside M1: v1temp.RollNo = 456, v2temp.RollNo = 123
After calling M1: v1.RollNo = 456, v2.RollNo = 123

In the above example when the references are swapped inside M1, they now refer to each
other’s objects, but the actual references in the Sub Main are also swapped, as shown by the
output.

Fall semester 2012 Page 26 of 36


In Sub Main (before
RollNo=123 V2 RollNo=456 calling M1)
V1

In Sub Main (after


V1 RollNo=123 V2 RollNo=456
calling M1)

In M1, before swap


V1temp V2temp

The variables are of Reference type, and their


references are copied by reference

V1temp V2temp In M1, after swap

Think of this scenario as: V1 and V1temp are two names for the same address. Changing the
value through any one of them will be reflected by the other. Changing the address for any
one of them will also change the address for the other.

Week-7
-Types of errors:
Syntax errors: Errors in program’s syntax such as a misspelled keyword, illegal statement
structures etc are syntax errors. These kinds of errors are caught by the compiler and are easy
to fix. If we set Option Explicit to On in Visual Studio IDE the IDE will notify us of errors.
Option Explicit On
Public Class SyntaxErr
Shared Sub Main()
Dim i As Intger = 4 ' Type Intger is not defined
Dem j As String = "Syntax Erros" ' comma, ')', or a valid
expression continuation expected
Console.ReadKey()
End Sub
End Class

Logic errors: Errors in program logic are sometimes the worst of error because they are very
difficult to catch. For example the following function Area() calculate the area of a circle but
the logic is incorrect, i-e instead of πr2 it uses πr3, therefore the result is wrong but neither a
compilation error nor a runtime error occurs.

Option Explicit On
Public Class LogicErr
Const PI As Double = 3.1416
Shared Function Area(ByVal radius As Integer) As Double
Area = PI * radius ^ 2
End Function
Shared Sub Main()
Dim rad As Integer = 3
Console.WriteLine("Area of circle with radius {0} is {1}", rad,
Area(rad))
Console.ReadKey()
End Sub
End Class

Fall semester 2012 Page 27 of 36


Runtime errors (exceptions): These are errors that occurs at runtime do to some unexpected
behavior of the program for example the program attempts to connect to a database that does
not exists or it tries to open a file must misspells the file name. If these errors are not handled
properly by the program then the program will crash if they do occur.

-Structured Exception Handling: Structured Exception Handling gives a proper way for
runtime error handling, throwing and raising. When a runtime error occurs CLR creates and
raises an object which is based on System.Exception class. Most exceptions are built-in but
users can also define their own exceptions.
The CLR creates a table for exceptions. This table contains an array for every method in the
program which stores information about what the runtime should do if an exception occurs.
But if there are no exception handlers for a method then its array in the table will be empty
and the error will pop up to the caller of the method till it finds a handler in which case the
runtime creates a new exception object. If no handler is found across the call stack then the
program will crash.
Code that includes exception-handling is called protected code.
We enclose the code that we expect can raise runtime errors in Try End Try block. Inside the
try block we can include one or more Catch blocks that will try to handle the exception. We
can also include a Finally block in the Try which is executed whether an exception occurs
or not. The following example shows the use of Try End Try block. It the user provides a
wrong file name then FileNotFoundException is generated and is handled properly.

Option Explicit On

Imports System.IO

Public Class ExceptionHandling


Shared Sub ReadFile(ByVal fileName As String)
Dim errMsg As String
Try
Dim fStream As New FileStream(fileName, FileMode.Open)
Dim sReader As New StreamReader(fStream)
Console.WriteLine(sReader.ReadToEnd)
fStream.Close()
Catch ex As FileNotFoundException
errMsg = "The FileNotFoundException has occurred" & vbCrLf _
& "The message is: " & ex.Message & vbCrLf _
& "The stack trace is: " & ex.StackTrace & vbCrLf _
& "The source is: " & ex.Source
Console.WriteLine(errMsg)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub

Shared Sub Main()


Dim fileName As String
Console.WriteLine("Enter file name with full path:")
fileName = Console.ReadLine()
Call ReadFile(fileName)
Console.ReadKey()
End Sub
End Class

If we include more than one catches then the catches should be in order from most specific to
most general. For example if in the above example the second catch Exception comes first

Fall semester 2012 Page 28 of 36


then FileNotFoundException will never get a chance. The IDE will issue a warming in this
case.
-Throwing our own exceptions:
Option Explicit On

Imports System.IO

Public Class MyException


Inherits IO.IOException
Private ErrMsg As String
Sub New()
ErrMsg = "Directory not found."
End Sub

Public Function GetErrMsg() As String


Return ErrMsg
End Function
End Class

Public Class ExceptionHandling


Shared Sub ReadFile(ByVal fileName As String)
Dim errMsg As String
Try
Dim fStream As New FileStream(fileName, FileMode.Open)
Dim sReader As New StreamReader(fStream)
Console.WriteLine(sReader.ReadToEnd)
fStream.Close()
Catch ex As FileNotFoundException
errMsg = "The FileNotFoundException has occurred" & vbCrLf _
& "The message is: " & ex.Message & vbCrLf _
& "The stack trace is: " & ex.StackTrace & vbCrLf _
& "The source is: " & ex.Source
Console.WriteLine(errMsg)
Catch ex As DirectoryNotFoundException
Throw New MyException()
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
Console.WriteLine("Finally block")
End Try
End Sub

Shared Sub Main()


Dim fileName As String
Console.WriteLine("Enter file name with full path:")
fileName = Console.ReadLine()
Try
Call ReadFile(fileName)
Catch ex As MyException
Console.WriteLine(ex.GetErrMsg())
End Try
Console.ReadKey()
End Sub
End Class

-Unstructured Exception Handling: Unstructured way of error trapping is enabled by using


the On Error statement. Once the error trap is enabled, any errors that occur will be handled
by the line label indicated by the Goto statement in the On Error statement. Following is the
same Sub Procedure from the above program that handled the exception with Try End Try but
this time it is using On Error statement.

Shared Sub ReadFile(ByVal fileName As String)


On Error GoTo errHandler
Dim fStream As New FileStream(fileName, FileMode.Open)
Dim sReader As New StreamReader(fStream)

Fall semester 2012 Page 29 of 36


Console.WriteLine(sReader.ReadToEnd)
fStream.Close()
Exit Sub

errHandler:
Console.WriteLine("Error trapped")
End Sub

-Error chaining: The following code shows how errors can chain deep and as Sub1 and
Sub2 does not include error trapping therefore the error bubbles up to MainCaller. It is very
difficult to debug in such scenario.

Sub MainCaller()
On Error GoTo errHandler
Call Sub1()
errHandler:
Console.WriteLine("Error trapped")
End Sub

Sub Sub1()
Call Sub2()
End Sub

Sub Sub2()
'runtime error
End Sub

We won’t be using this unstructured exception handling.

Week-8
-Object Oriented Concept: Program objects model real world objects with attributes and
behaviors.

-Declaring Classes (Encapsulation): A class is a template for creating objects and it


encloses the attributes and behaviors of an object thereby provide data hiding. Here is the
general structure of declaring a class:
[ <attrlist> ] [ Public | Private | Protected | Friend | Protected Friend ]
[ Shadows ] [ MustInherit | NotInheritable ]
Class class_name
[ statements ]
End Class

Public Class Student


Private StudName As String

Public Property StudentName() As String


Set(ByVal Value As String)
StudName = Value
End Set
Get
Return StudName
End Get
End Property
End Class

-Declaring Objects:
Dim stud1 As New Student

Fall semester 2012 Page 30 of 36


-Overloading: Including more than one method, constructor, or property with the same name
but different parameter lists in the same namespace.
Module Module1
Public Class Math
Public Overloads Function Square(ByVal num As Integer) As Integer
Return num * num
End Function

Public Overloads Function Square(ByVal num As Double) As Double


Return num * num
End Function
End Class

Sub Main()
Dim MathObj As New Math
Console.WriteLine("Square of 3 is {0}", MathObj.Square(3))
Console.WriteLine("Square of 3.5 is {0}", MathObj.Square(3.5))
Console.ReadKey()
End Sub
End Module

Week 9:

-Encapsulation and Inheritance:

-Overriding: Defining a method in the derived class with the same name and parameter list
as in the base class.
Module Module1
Public Class Fan
Protected SpeedV As Integer
Sub New()
Console.WriteLine("Super class constructor called")
SpeedV = 0
End Sub
Public ReadOnly Property Speed As Integer
Get
Return SpeedV
End Get
End Property

Public Overridable Function SpeedUp() As Integer


SpeedV = SpeedV + 1
PrintMessage("Fan")
Return Speed
End Function

Public Sub PrintMessage(ByVal msg As String)


Console.Write("Speed of {0} is: ", msg)
End Sub

End Class

Public Class SuperFan


Inherits Fan
Public Overrides Function SpeedUp() As Integer
SpeedV = SpeedV + 5
PrintMessage("Super Fan")
Return Speed
End Function
End Class

Sub Main()
Dim SuperFanObj As New SuperFan
Dim FanObj As Fan = SuperFanObj
Console.WriteLine(FanObj.SpeedUp())

Fall semester 2012 Page 31 of 36


Console.ReadKey()
End Sub
End Module
Output:
Super class constructor called
Speed of Super Fan is: 5

In the above program the function SpeedUp() in the derived class SuperFan is overriding the
same function in the base class.
In Sub Main() we have assigned an object of the derived class to a reference of the base class.
The statement FanObj.SpeedUp()invokes the derived class function instead of the base class.
This is polymorphism.
Note that if we remove the keyword Overridable from SpeedUp()in the base class and
Overrides from the derived class then the output of this program will be:

Super class constructor called


Speed of Fan is: 1

This is because the base class function SpeedUp()is no more overriding the base class
function and we have used the base class reference to call the function. Therefore the base
class function is invoked.

Benefits of inheritance and polymorphism: Inheritance is useful when we have a class that
we do not want to change but need to add some extra functionality to it. This way we can use
the existing functions of the base class plus those we add to the derived class.
Using polymorphism we achieve dynamic message to function binding.

If a member function is declared with MustOverride then it cannot have a body and the
derived class must override this method. If a class contains a MustOverride method then that
class should be declared as MustInherit
Instantiating an object of a MustInherit class is a compile time error.
Module Module1
Public MustInherit Class A
Public MustOverride Function GetName() As String
'Return "Class A"
'End Function
End Class

Public Class B
Inherits A
Public Overrides Function GetName() As String
Return "Class B"
End Function
End Class

Sub Main()
Dim bObj As New B
Dim aRef As A = bObj
Console.WriteLine(aRef.GetName())
Console.ReadKey()
End Sub
End Module

-Interfaces:
Module Module1
Public Interface A
Function GetName() As String
End Interface

Fall semester 2012 Page 32 of 36


Public Class B
Implements A

Public Function GetName1() As String Implements A.GetName


Return "Class B"
End Function
End Class

Public Class C
Implements A

Public Function GetName1() As String Implements A.GetName


Return "Class C"
End Function
End Class

Sub Main()
Dim ObjB As New B
Dim ObjC As New C

Dim RefA As A = ObjB


Console.WriteLine(RefA.GetName())
RefA = ObjC
Console.WriteLine(RefA.GetName())
Console.ReadKey()
End Sub
End Module

Output:
Class B
Class C

-Raising and handling events: Events are notifications that cause something to happen or
occur in response to something happening. Events can be raised and consumed. They are
declared with the event signature using the Event keyword and raised with the RaiseEvent
statement, and handled with the Handles clause. An Event cannot have a return value. In the
following example SetTimer raises an event called Ring whenever its field timeUp is set to
“Go”. The WithEvents keyword tells VB that the variable is capable of raising events. The
sub procedure Handle_Ring_Event handles this event.

Option Explicit On

Module MiscModule
Public Class SetTimer
Private timeUp As String
Public Event Ring(ByVal ringTone As String)
Public Property TimeIsUp() As String
Get
Return timeUp
End Get
Set(ByVal Value As String)
timeUp = Value
If Value = "9:00" Then
RaiseEvent Ring(timeUp)
End If
End Set
End Property
End Class

Dim WithEvents newTimer As New SetTimer


Private Sub Handle_Ring_Event(ByVal currTime As String) Handles
newTimer.Ring
Console.WriteLine("Tic Tic at {0}", currTime)

Fall semester 2012 Page 33 of 36


End Sub

Sub Main()
newTimer.TimeIsUp = "9:00"
Console.WriteLine("After events")
Console.ReadKey()
End Sub
End Module
Output:
Tic Tic at 9:00
After events

We can also add Handlers for Events dynamically with AddHandler statement. In the following
example the line AddHandler newTimer.Ring, AddressOf Handle_Ring_Event2
Adds a handler Handle_Ring_Event2 for newTimer.Ring event. The AddressOf statement
specifies the handler that will be called when the event mentioned in AddHandler is triggered.
It implicitly creates an instance of a delegate that refers to a specific procedure.
Note that we can also add multiple handlers for the same event as the example shows.
Dim WithEvents newTimer As New SetTimer
Private Sub Handle_Ring_Event2(ByVal currTime As String) Handles newTimer.Ring
Console.WriteLine("Tic Tic in Handler2 at {0}", currTime)
End Sub
Private Sub Handle_Ring_Event(ByVal currTime As String) Handles newTimer.Ring
AddHandler newTimer.Ring, AddressOf Handle_Ring_Event
AddHandler newTimer.Ring, AddressOf Handle_Ring_Event2
Console.WriteLine("Tic Tic in Handler1 at {0}", currTime)
End Sub
Output:
Tic Tic in Handler1 at 9:00
Tic Tic in Handler2 at 9:00
After events

Delegates: Delegates can refer to methods and are useful when we need an intermediary
between a calling procedure and the caller. They are like C++ function pointers but are type-
safe.
Module MiscModule
Function Sum(ByVal n1 As Integer, ByVal n2 As Integer) As Integer
Return (n1 + n2)
End Function

Function Mult(ByVal n1 As Integer, ByVal n2 As Integer) As Integer


Return n1 * n2
End Function
' define a delegate function that can point to a function accepting two integers
and returning an integer
Delegate Function SumMult(ByVal n1 As Integer, ByVal n2 As Integer) As Integer

Class SumMultClass
Private num1, num2 As Integer
Property Number1() As Integer
Get
Return num1
End Get
Set(ByVal value As Integer)
num1 = value
End Set
End Property
Property Number2() As Integer
Get
Return num2
End Get

Fall semester 2012 Page 34 of 36


Set(ByVal value As Integer)
num2 = value
End Set
End Property
Public Function AddOrMultiply(ByVal addMult As SumMult) As Integer
Return addMult(num1, num2)
End Function
End Class

Sub Main()
Dim SumMultObj As New SumMultClass
SumMultObj.Number1 = 2
SumMultObj.Number2 = 4
Console.WriteLine("Sum of {0}, {1} is: {2}", SumMultObj.Number1,
SumMultObj.Number2, SumMultObj.AddOrMultiply(AddressOf Sum))
Console.WriteLine("Product of {0}, {1} is: {2}", SumMultObj.Number1,
SumMultObj.Number2, SumMultObj.AddOrMultiply(AddressOf Mult))
Console.ReadKey()
End Sub
End Module

Week 10
Common properties
Design Vs Run time

Week: 11
Name, Size, Location, Enabled, Visible,
Back color, fore color, Font, Text

Week: 12
Vb.net forms
Working with different controls in vb.net
Textbox Control
Common Properties
Read only, Password char, Max length, Multi line,
Border style, Scrollbar, Text align
Button Control
Common Properties
Text, Flat style, Image, Image align, Text align

Week: 13
Common Properties
Checkbox and Radio Controls
Appearance, Checked, Check state, Text, flat style
Listbox Control
Scrollbars, Items, Sorted, Size
Combobox Control
Items, Max length, Selected item

Fall semester 2012 Page 35 of 36


Week: 14
Built-in Dialog Controls
Open file Dialog
Save file Dialog
Font Dialog

Week: 15
Rich Text Box
Properties
Autosize, Borderstyle, Lines, Selectionfont, Selectioncolor
Methods
Clear, Load file, save file, Undo, Redo, Copy, Paste

Week: 16

Project

Total Marks: 100

Recommended Books
Visual Basic.net Bible By Bill Evjen, Jason Beres
Visual Basic.net Mastering series

Fall semester 2012 Page 36 of 36

You might also like