Professional Documents
Culture Documents
Visual Programing1 Notes v2
Visual Programing1 Notes v2
Visual Programing1 Notes v2
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.
-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.
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
-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
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.
-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.
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.
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.
Week-2
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.
The following programs show that copying one value type to another value type copies the
contents, while for reference type the reference is copied.
-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.
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
-Declaring Constants: We need to specify the value of the constant when we declare it.
-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)
-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.
-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.
Exception:
An unhandled exception of type 'System.InvalidCastException' occurred in
Microsoft.VisualBasic.dll
-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.
-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)
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";
}
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)>
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()
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
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.
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.
-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.
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.
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()
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
-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"
-Relational operators (>, <, >=, <=, =, <>): These operators takes two operands and the
results is either True of False.
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.
-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
-Premature exit from a loop: To exit/terminate a do while loop before the initial set
condition we use Exit Do
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
-For Next: General structure is given below. Bracketed terms are optional:
For Counter = <StartValue> To <EndValue> [Step] [StepValue]
[Statement(s)]
[Exit For]
Next [Counter]
-For Each: General structure is given below. Set is a collection like an array.
For Each i In Set
Another example:
Public Class Student
Private StudName As String
Private StudRollNo As Integer
Console.ReadKey()
End Sub
End Class
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.
The second statement creates a new string object with value “Welcome to Peshawar” and
assigs it to the reference str.
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.
Reverse: Reverses the order of characters in a string and returns a collection of chars.
Dim str As String = "Visual Programming"
Output:
gnimmargorP lausiV
As the Reverse function returns an IEnumerable collection therefore to print the reversed
string we can use a For Each loop.
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
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.
To ignore case use StringComparison.OrdinalIgnoreCase i-e. use Order but Ignore Case.
Console.WriteLine(String.Equals("alpha", "Alpha",
StringComparison.OrdinalIgnoreCase)) ' returns: True
LastIndexOf: Returns the index of the last occurrence of the specified character in a string.
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.
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
-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
-Property Procedures: Properties are used to get/set fields of a class, structure or module.
Console.ReadKey()
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
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
1 V2temp 2
V1temp In M1
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
The swapping inside M1 also affect the variables declared in Sub Main()
1 V2 2
V1 In Sub Main
V1temp V2temp In M1
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
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
V1temp V2temp In M1
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
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
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
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.
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
-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
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
Imports System.IO
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
Week-8
-Object Oriented Concept: Program objects model real world objects with attributes and
behaviors.
-Declaring Objects:
Dim stud1 As New Student
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:
-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
End Class
Sub Main()
Dim SuperFanObj As New SuperFan
Dim FanObj As Fan = SuperFanObj
Console.WriteLine(FanObj.SpeedUp())
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:
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
Public Class C
Implements A
Sub Main()
Dim ObjB As New B
Dim ObjC As New C
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
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
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
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
Week: 15
Rich Text Box
Properties
Autosize, Borderstyle, Lines, Selectionfont, Selectioncolor
Methods
Clear, Load file, save file, Undo, Redo, Copy, Paste
Week: 16
Project
Recommended Books
Visual Basic.net Bible By Bill Evjen, Jason Beres
Visual Basic.net Mastering series