You are on page 1of 54

Unit 2

Basic Program structure


A VB.Net program basically consists of the following

parts:
Namespace declaration
A class or module
One or more procedures
Variables
The Main procedure
Statements & Expressions
Comments

Hello World
Imports System Module Module1
'This program will display Hello World
Sub Main()
Console.WriteLine("Hello World")
Console.ReadKey()
End Sub
End Module

Basic Data Types


Data Type

Storage
Allocation

Value Range

Boolean

Depends on
implmnts

True or False

Byte

1 byte

0 through 255 (unsigned)

Char

2 bytes

0 through 65535 (unsigned)

Date

8 bytes

0:00:00 (midnight) on January 1, 0001 through 11:59:59


PM on December 31, 9999

Decimal

16 bytes

0 through +/79,228,162,514,264,337,593,543,950,335

Double

8 bytes

1.79769313486231570E+308through4.94065645841246544E-324, for negative values


4.94065645841246544E-324through
1.79769313486231570E+308, for positive values

Integer

4 bytes

-2,147,483,648 through 2,147,483,647 (signed)

Long

8 bytes

-9,223,372,036,854,775,808 through
9,223,372,036,854,775,807(signed)

Data Type

Storage
Allocation

Value Range

Object

4 bytes on Any type can be stored in a variable of type Object


32-bit 8 bytes
on64-bit
platform

SByte

1 byte

-128 through 127 (signed)

Short

2 bytes

-32,768 through 32,767 (signed)

Single

4 bytes

-3.4028235E+38 through -1.401298E-45 for negative


values;1.401298E-45 through 3.4028235E+38 for
positive values

String

Depends on
implemnts

0 to approximately 2 billion Unicode characters

UInteger

4 bytes

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

ULong

8 bytes

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

UserDefined

Depends on Each member of the structure has a range determined by


implementin its data type and independent of the ranges of the other
g platform
members

UShort

2 bytes

0 through 65,535 (unsigned)

Variable Declaration
[ < attributelist> ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [
Static ]] [ Read Only ] Dim [ WithEvents ] variablelist
attributelist is a list of attributes that apply to the variable. Optional.
accessmodifier defines the access levels of the variables, it has values as Public, Protected, Friend, Protected Friend and Private. Optional.
Shared declares a shared variable, which is not associated with any specific
instance of a class or structure, rather available to all the instances of the
class or structure. Optional.
Shadows indicate that the variable re-declares and hides an identically
named element, or set of overloaded elements, in a base class. Optional.
Static indicates that the variable will retain its value, even when the after
termination of the procedure in which it is declared. Optional.
Read-only means the variable can be read, but not written. Optional.
WithEvents specifies that the variable is used to respond to events raised by
the instance assigned to the variable. Optional.
Variablelist provides the list of variables declared.

Variable Declaration
Module variablesNdataypes
Sub Main()
Dim a As Short
Dim b As Integer
Dim c As Double
a = 10
b = 20
c=a+b
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c)
Console.ReadLine()
End Sub
End Module

Option Strict
Option Strict [On Off]
By default Option Strict is Off

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal
e As System.EventArgs) Handles Button1.Click
Dim longNum As Long
Dim intNum As Integer
longNum = 12345
intNum = longNum
MsgBox(intNum)
End Sub
End Class

Option Strict
The program is a normal vb.net program and is in default Option

Strict Off .
Because its Option Strict Off we can convert the value of Long to an
Integer.
By adding the below line we can turn strict option on.
Option Strict On

When you write this source code the compiler will shows the
message
"Option Strict On disallows implicit conversions
from 'Long' to 'Integer'"
The compiler generate error because in the program we
put "Option Strict On" and prevent the program from
automatic conversion.

Option Explicit
By default it is declared ON.

When Option Explicit is turned off, you can use any

variable name without first declaring it.


The first time you use a variable name, VB allocates a
new variable of Object data type.
Z = myTotal + 1
Here Z and myTotal are not declared.
But when u turn it off , it generates error showing
variable declaration is compulsory.

Option Compare
The Option Compare statement must appear in a module before

any procedures.
The
Option
Compare
statement
specifies
the
string
comparison method (Binary, Text) for a module.
If a module doesn't include an Option Compare statement, the
default text comparison method is Binary.
Option Compare Binary results in string comparisons based on
a sort order derived from the internal binary representations of the
characters
A<B<E<Z<a<b<e<z<
Option Compare Text results in string comparisons based on a caseinsensitive text sort order determined by your system's locale.
(A=a) < ( =) < (B=b) < (E=e) < (=) < (Z=z) < (=)

Operators
Arithmetic Operators
Operator Description
^

Raises one operand to the power of another

Adds two operands

Subtracts second operand from the first

Multiplies both operands

Divides one operand by another and returns a


floating point result

Divides one operand by another and returns an


integer result

MOD

Modulus Operator and remainder of after an


integer division

Comparison Operator
Operator

Description

==

Checks if the values of two operands are equal or not; if yes, then
condition becomes true.

<>

Checks if the values of two operands are equal or not; if values are
not equal, then condition becomes true

>

Checks if the value of left operand is greater than the value of right
operand; if yes, then condition becomes true

<

Checks if the value of left operand is less than the value of right
operand; if yes, then condition becomes true.

>=

Checks if the value of left operand is greater than or equal to the


value of right operand; if yes, then condition becomes true

<=

Checks if the value of left operand is less than or equal to the value of
right operand; if yes, then condition becomes true.

Logical Operators
Operator

Description

And

It is the logical as well as bitwise AND operator. If both the


operands are true, then condition becomes true.

Or

It is the logical as well as bitwise OR operator

Not

It is the logical as well as bitwise NOT operator. Use to reverses


the logical state of its operand.

Xor

It is the logical as well as bitwise Logical Exclusive OR operator. It


returns

AndAlso

It is the logical AND operator. It works only on Boolean data. It


performs short-circuiting.

OrElse

It is the logical OR operator. It works only on Boolean data. It


performs short-circuiting.

IsFalse

It determines whether an expression is False

IsTrue

It determines whether an expression is True.

Assignment Operators
Operator Description
=

Assigns values from right side operands to left side operand

+=

It adds right operand to the left operand and assigns the result to left
operand

-=

It subtracts right operand from the left operand and assigns the result to
left operand

*=

It multiplies right operand with the left operand and assigns the result to
left operand

/=

It divides left operand with the right operand and assigns the result to left
operand (floating point division)

\=

It divides left operand with the right operand and assigns the result to left
operand (Integer division)

^=

It raises the left operand to the power of the right operand and assigns the
result to left operand.

<<=

Left shift AND assignment operator

>>=

Right shift AND assignment operator

&=

Concatenates a String expression to a String variable or property and

Decision Making
If - Then statement

If condition Then
[Statement(s)]
End If
If (a <= 20) Then
c= c+1
End If

Decision Making (cntd)


If(condition)Then

'statement(s) will execute if the condition is true


Else
'statement(s) will execute if the condition is false
End If
The If...Else If...Else Statement
If(condition1)Then
' Executes when the condition1 is true
ElseIf(condition2)Then
' Executes when the condition2 is true
ElseIf(condition3)Then
' Executes when the condition3 is true
Else
' executes when the none of the above condition is true
End If

Decision Making (cntd)


Nested If

If(condition1)Then
'Executes when the condition1 is true
If(condition2)Then
'Executes when the condition2 is true
End If
End If

Decision Making (cntd)


Select Case

Select [ Case ] expression


[ Case expressionlist [ statements ] ]
[ Case Else [ elsestatements ] ]
End Select
Dim grade As Char
Select grade
Case "A"
Console.WriteLine("Excellent!")
Case "B", "C
Console.WriteLine("Well done")
Case "D
Console.WriteLine("You passed")
Case "F
Console.WriteLine("Better try again")
Case Else
Console.WriteLine("Invalid grade")
End Select

Loops
Do while

Do { While | Until } condition


[ statements ]
[ Continue Do ]
[ statements ]
[ Exit Do ]
[ statements ]
Loop
-orDo
[ statements ]
[ Continue Do ]
[ statements ]
[ Exit Do ]
[ statements ]
Loop { While | Until } condition

Loops (cntd)
Do
Console.WriteLine("value of a: {0}", a)
a=a+1
Loop While (a < 20)

Loops (cntd)
For loop

For counter [ As datatype ] = start To end [ Step step ]


[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]

Loops (cntd)
For a = 10 To 20 step 2
increments the counter by two
Console.WriteLine("value of a: {0}", a)
Next

Loops (cntd)
For Each element [ As datatype ] In group

[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ] Next [ element ]

Loops (cntd)
Dim anArray() As Integer = {1, 3, 5, 7, 9}
Dim arrayItem As Integer
'displaying the values
For Each arrayItem In anArray
Console.WriteLine(arrayItem)
Next
Console.ReadLine()

Loops (cntd)
While condition
[ statements ]
[ Continue While ] [ statements ]
End While
While a < 20
Console.WriteLine("value of a: {0}", a)
a=a+1
End While

Date and Time


Property

Description

Date

Gets the date component of this instance.

Day

Gets the day of the month represented by this instance

DayOfWeek Gets the day of the week represented by this instance

DayOfYear

Gets the day of the year represented by this instance.

Hour

Gets the hour component of the date represented by this instance.

Kind

Gets a value that indicates whether the time represented by this


instance is based on local time, Coordinated Universal Time (UTC),
or neither.

Millisecond Gets the milliseconds component of the date represented by this


instance.
Minute

Gets the minute component of the date represented by this instance

Month

Gets the month component of the date represented by this instance.

Now

Gets a DateTime object that is set to the current date and time on
this computer, expressed as the local time.

Date and Time (cntd..)


Second

Gets the seconds component of the date represented by


this instance.

Ticks

Gets the number of ticks that represent the date and time of this
instance.

TimeOfDay Gets the time of day for this instance.


Today

Gets the current date.

UtcNow

Gets a DateTime object that is set to the current date and time on
this computer, expressed as the Coordinated Universal Time (UTC).

Year

Gets the year component of the date represented by this instance.

Date and Time (cntd..)


Module Module1 Sub Main()

'DateTime constructor: parameters year, month, day, hour, min, sec


Dim date1 As New Date(2012, 12, 16, 12, 0, 0)
'initializes a new DateTime value
Dim date2 As Date = #12/16/2012 12:00:52 AM#
'using properties
Dim date3 As Date = Date.Now
Dim date4 As Date = Date.UtcNow
Dim date5 As Date = Date.Today
Console.WriteLine(date1)
Console.WriteLine(date2)
Console.WriteLine(date3)
Console.WriteLine(date4)
Console.WriteLine(date5)
Console.ReadKey()
End Sub
End Module

Type Conversions
Dim dbvalue As Double
Dim intvalue As Integer
Dbvalue =6.4859
intValue=Cint(dbvalue)
converts double to integer
Numvalue=Val(Stringlvariable)
Numvalue=Val(66)
Stringvariable=Str(NumValue)
Stringvarialbe=Str(66)

CBool

Convert to Boolean data type

CByte

Convert to Byte data type

CChar

Convert to Char data type

CDate

Convert to Date data type

CDbl

Convert to Double data type

CInt

Convert to Integer data type

Clng

Convert to Long data type

Cobj

Convert to Object data type

CSByte

Convert to Sbyte data type

CShort

Convert to Short data type

CSng

Convert to Single data type

Cstr

Convert to String data type

Arrays
Dim Data(30) As Integer

Dim Strings(10) As String


Dim TwoArray(20,40) As integer
Dim Data ()={10,3,2}

Dim threeDIntArray(10, 10, 10) As Integer


Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4,

8}}

Dynamic Arrays
Use Dim statement to declare an array with empty

parentheses to declare a dynamic array.


Dynamic arrays can be dimensioned or redimensioned
with ReDim statement.
ReDim [Preserve ] Varname(subscripts)
Preserve key word is used to preserve the data in an existing
array when you change the size of the last dimension.
Dim Dynastrings As String
ReDim Dynastrings(10)
Need more data
ReDim Dynastrings(100)

Dynamic Arrays (cntd)


Dim marks() As Integer
ReDim marks(2)
marks(0) = 85
marks(1) = 75
marks(2) = 90
ReDim Preserve marks(10)
marks(3) = 80
marks(4) = 76
marks(5) = 92
marks(6) = 99
marks(7) = 79
marks(8) = 75
For i = 0 To 10
Console.WriteLine(i & vbTab & marks(i))
Next i

Exception Handling
On Error Go to handler

Sub main()
Dim int1=0, int2 = 1 int3 as Integer
On Error Goto Handler
Int3 = int2/int1
System.Console.Writeline(the answer is , int3)
Exit sub
Handler :
System.console.Writeline(Divide by Zero error)
Resume Next
End Sub

Try Catch
Sub main()
Dim int1=0, int2 = 1 int3 as Integer
Try
Int3 = int2/int1
System.Console.Writeline(the answer is , int3)
Catch e As Exception
System.console.writeline(e.ToString)
End Try
End Sub

Try catch Finally


Sub main()
Dim int1=0, int2 = 1 int3 as Integer
Try
Int3 = int2/int1
System.Console.Writeline(the answer is , int3)
Catch e As Exception
System.console.writeline(e.ToString)
Finally
System.Console.Writeline(enter non zero numbers)
End Try
End Sub

Throw
If an exception occurs during the evaluation of an

expression, the language runtime automatically


throws the appropriate exception.
If an exception must be thrown programmatically,
you would use the throw statement.
If age < 0 Then
' throw an argument out of range exception if the age isless than
zero.
Throw New ArgumentOutOfRangeException("Age Cannot Be
Negative ")
End If

GDI+
GDI stands for Graphic Device Interface. In

Microsoft Windows, GDI is a way to work with


paining graphic objects such as painting on windows,
forms or other media.
GDI is a set of C++ classes, which provides
functionality to render data to a program to
hardware devices with the help of device drivers.
GDI sits between the program and the hardware and
transfer data from one to other.
GDI+ is next evolution of GDI.

The namespaces in GDI+


System.Drawing
This is the core GDI+ namespace. It defines objects for basic
rendering (fonts, pens, basic brushes, etc.)
System.Drawing.Drawing2D
This gives you objects for more advanced two dimensional vector
graphics.
Some of them are gradient brushes, pen caps, and geometric
transforms.
System.Drawing.Imaging
If you want to change graphical images - that is, change the palette,
extract image metadata, manipulate metafiles, and so forth - this is
the one you need.

System.Drawing.Printing

To render images to the printed page, interact with the


printer itself, and format the overall appearance of a
print job, use the objects here.
System.Drawing.Text
You can use collections of fonts with this namespace.

GDI+ example
Dim g As Graphics = e.Graphics
Dim p As Pen = New Pen(Color.Crimson, 3)
Dim P1 As Point = New Point(10, 10)
Dim P2 As Point = New Point(100, 40)
g.DrawLine(p, P1, P2)
g.DrawLine(New Pen(Color.Crimson, 3), 10,
10, 100, 40)
e.Graphics.DrawLine(New
Pen(Color.Crimson, 3), P1, P2)

Visiblity And Scope of variables


Public:- Gives public access no restriction on their
accessibilty
Private:- Accessible only within their class procedures
and functions.
Protected :- Accessible only from within their own
class or from a class derived from that class.
Friend :- Accessible that contains their declaration , as
well as anywhere else in the same assembly.
Protected Friend :- Can be used by the code in the
same assembly, as well as by code in derived class

Shared Keyword
Using shared keyword makes a member into a class
member, there is no need to create an object to access
that member.
Public Class Maths
Shared Function Add(Byval X As Integer,ByVal Y As
Integer) As Integer
Return X+Y
End Function
End Class
Textbox3.text=Maths.Add(Textbox1.Text,Textbox2.Text)

Constructors
Constructor is special method of a class which is

used to initialize the data members of the class.


It is a sub procedures declared with NEW keyword.
It does not return any value.
A class can have multiple constructors
It is not mandatory to declare a constructor, the
compiler invokes it automatically.

Constructors(cntd)
Class circle
Private radius as Integer
Private Const PI As Single = 3.14f
Public Sub New (ByVal x As Integer)
radius=x
End Sub
Public Sub area()
Dim res As Single = PI*radius*radius
Console.writeline(Area of a circle is &res)
End Sub
End Class
Module Program
Sub Main()
Dim obj As New circle(5)
Obj.area()
Console.Read()
End Sub
End Module

Abstract Class
Inheritance is a way to extend the functionalities of a class in

other classes which are derived from it.


A derived class extends the functionalities of its base by
adding new variables and methods inside it.
The class which exposes its members for use by other classes
is known as base class.
The class which inherits the functionalities of the base class is
known as derived class.
Abstract classes are same like base classes with the difference
that the methods declared inside the abstract classes , known
as abstract method, do not have method bodies.
The actual implementation of the methods is done in the
classes derived from the abstract classes.

Characteristic of Abstract Class


It cannot be instantiated by its own, it must be

inherited first.
It can contain any number of abstract methods.
It can also contain non abstract methods.
It is declared using the MustInherit keyword.

Characteristic of Abstract Method


It is declared using the MustOverride keyword
It is found only in Abstract classes
It has its declaration in the abstract class i.e name ,its

return type, its parameters , and the parameters data


types.
It must be overridden in the derived class.
Public MustInherit Class ClassName
Public Mustoverride Sub sub procedure-name()
Public Mustoverride Function function-name() as returntype
End Class

Interface
It is not possible for a class to inherit simultaneously

from more than one base class.


A class can implement multiple interfaces.
Do not have actual implementation ,only specify the
parameters they will take and the types of value they
will return.
Class implementing interface guarantees to provide
an implementation of the members defined in the
interface.

Characteristic of interface
It is declare in the same way as we declare classes.

It is declared using interface keyword.


It contains only method declaration, the methods do

not have body containing the code.


Class implementing interface compulsorily use all
declared methods else compiler will raises an error.
Public Interface IMyName
Sub displayMyName()
End Interface

Try Catch Finally