Visual
Visual
NET
Adnan Vallippadan
[email protected]
Contents
Introduction to .NET Framework ................................................................................................................. 4
VB.NET .......................................................................................................................................................... 4
Console Applications .................................................................................................................................... 4
Web Applications ......................................................................................................................................... 5
Windows Application ................................................................................................................................... 5
Difference between Windows Application and Web Application .............................................................. 5
Keywords ...................................................................................................................................................... 6
Data Types in VB.NET ................................................................................................................................... 6
Numeric Data Types ................................................................................................................................. 6
Non Numeric Data Types ......................................................................................................................... 6
Variables ....................................................................................................................................................... 6
Declaring Variables................................................................................................................................... 7
Assigning values to variables ................................................................................................................... 7
Variables vs Constants ............................................................................................................................. 7
Type Conversion Functions ...................................................................................................................... 7
Operators in VB.NET..................................................................................................................................... 7
Logical Operators in detail ........................................................................................................................... 9
Starting with Console Applications............................................................................................................ 10
Console.Write Method ............................................................................................................................... 11
Console.WriteLine Method ........................................................................................................................ 12
Differences between Console.Write() & Console.WriteLine().................................................................. 12
Console.ReadLine Method ......................................................................................................................... 12
Console.Read Method ................................................................................................................................ 12
Reading Values into Variables from standard input devices .................................................................... 12
Adding Commands in a Program ............................................................................................................... 13
Displaying a Message .................................................................................... Error! Bookmark not defined.
Selection Statements ................................................................................................................................. 14
Iteration Statement.................................................................................................................................... 16
1. While…End While Statements ....................................................................................................... 17
2. Do While…Loop Statements .............................................................................................................. 17
3. Do Until…Loop .................................................................................................................................... 18
4. For…Next Statements ........................................................................................................................ 18
5. For Each…Next Statements ................................................................................................................ 19
6. Do…Loop While Statements .................................................................................................................. 19
7. Do…Loop Until Statements ................................................................................................................ 20
Arrays ...................................................................................................................................................... 21
Object Oriented Programming................................................................................................................... 24
OOP & VB.Net............................................................................................................................................. 27
Introduction to .NET Framework
.NET is a software framework which is designed and developed by Microsoft. The first version
of .Net framework was 1.0 which came in the year 2002. In easy words, it is a virtual machine
for compiling and executing programs written in different languages like C#, VB.Net etc.
It is used to develop Console applications, Form-based applications, Web-based applications,
and Web services. It is used to build applications for Windows, phone, web etc. It provides a lot
of functionalities and also supports industry standards.
.NET Framework supports more than 60 programming languages in which 11 programming
languages are designed and developed by Microsoft.
VB.NET
Visual Basic .NET (VB.NET) is an object-oriented computer programming language implemented
on the .NET Framework.
Console Applications
A console application is a computer program designed to be used via a text-only computer
interface, such as a text terminal, the command line interface of some operating systems (Unix,
DOS, etc.). It doesn’t have any graphical user interface. Console Applications will have character
based interface.
Figure 1
Web Applications
A web-based application is any program that is accessed over a network connection using HTTP,
rather than existing within a device’s memory. Web-based applications often run inside a web
browser. However, web-based applications also may be client-based, where a small part of the
program is downloaded to a user’s desktop, but processing is done over the internet on an
external server.
Web-based applications are also known as web apps.
Windows Application
Windows Application is a user build application that can run on a Windows platform. The
windows application has a graphical user interface that is provided by Windows Forms.
Windows forms provide a variety of controls including Button, TextBox, Radio Button,
CheckBox, and other data and connection controls. You can easily design a web application
using an IDE Microsoft Visual Studio using a variety of languages including C#, Visual Basic, C++,
J# and many more.
Figure 2
Variables
A Variable is an identifier, that denotes a storage space in memory. Every variable has a type
which determines which values are to be stored In it.
While naming a variable we should follow a set of rules as given below
A variable name can only contain alphabets, digits, and underscores.
A variable name should not begin with a number or digit.
A variable name cannot contain a blank space
Keywords cannot be used as variable names.
Declaring Variables
Variables are required using the Dim statement.
Syntax : Dim Var_Name As Type
We can declare more than one variables using Dim Statement seperated by commas, as given
below.
Dim Var_Name1 As Integer,Var_Name2 As String….
We can assign a value to the variable at the time of declaration itself or by using separate
statements.
Variables vs Constants
Data can be stored as variables & constants.
The content or value of a variable can be change at any time during the program, where as
constants not.
Const PI = 3.14
Operators in VB.NET
An operator is a symbol that is used to perform an operation on one or more expressions,
called operands.
Different types operators are :
Arithmetic Operators
Assignment Operators
Shorthand Assignment Operator
Concatenation Operator
Comparison Operator
Logical Operators
Miscellaneous Operators
Arithmetic Operators
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Integer Division (\)
Exponentiation (^)
Mod (%)
Assignment Operators
A=13
B=C
D=A+B
Sum=0
Fact=1
Shorthand Assignment Operator
A+=B
A-=B
A*=B
A/=B
A^=B
Concatenation Operator
In VB.NET we uses two operators for concatination.
‘+’ & ‘&’.
‘+’ is used to concatenate same data types,
‘&’ is used to concatenate different types of data types
Comparison Operator
Equal to (=)
Not Equal to (<>)
Less than (<)
Greater than (>)
Less than or equal to (<=)
Greater than or equal to (>=)
Is
IsNot
Like
Logical Operators
Not Operator
And Operator
Or Operator
Xor Operator
AndAlso Operator
OrElse Operator
Miscellaneous Operators
AddressOf
GetType
TypeOf
If
Function Expression
Condition Output
True False
False True
2. And Operator
AND returns true only if both operands are true and otherwise false.
3. Or Operator
If any of its arguments are true (or both), it returns true, otherwise it returns false.
4. Xor Operator
If any of one conditions becomes true, and remaining one becomes false, output
becomes true.
5. AndAlso Operator
6. OrElse Operator
Figure 3
The console code window comprises of modules, where the main module is module1, we can
add a module by clicking on project on menubar and click Add Module.
Figure 4
Figure 5
We can write the program codes inside the sub menu or between sub Main() & End Sub.
Console.Write Method
Writes the text representation of the specified value or values to the standard output stream.
Console.Write("Hiii")
Console.Write("Good Morning")
Console.ReadLine()
Output :
HiiiGood Morning
Console.WriteLine Method
Writes the specified data, followed by the current line terminator, to the standard output
stream.
Console.WriteLine("Hiii")
Console.WriteLine("Good Morning")
Console.ReadLine()
Output :
Hiii
Good Morning
Console.ReadLine Method
Reads the next line of characters from the standard input stream.
The ReadLine method reads a line from the standard input stream.
If the standard input device is the keyboard, the ReadLine method blocks until the user presses
the Enter key.
One of the most common uses of the ReadLine method is to pause program execution before
clearing the console and displaying new information to it, or to prompt the user to press the
Enter key before terminating the application.
Console.Read Method
Reads the next character from the standard input stream.
Module Module1
Sub Main()
Dim a As Integer = 13, b As String = "Hello", c As Integer, d As Integer
Console.WriteLine("Enter 2 Numbers")
c = CInt(Console.ReadLine())
d = CInt(Console.ReadLine())
Console.WriteLine(a)
Console.WriteLine(b)
Console.WriteLine("C = " & c & " D = " & d)
Console.ReadLine()
End Sub
End Module
Sample Pgm
Module BasicPgm1
Sub Main()
Dim A As Integer, B As Integer, C As Integer, D As Integer, E As Integer, F As Integer, G As
Integer, K As Integer
Console.WriteLine("Enter two numbers")
A = CInt(Console.ReadLine())
B = CInt(Console.ReadLine())
C=A+B
Console.WriteLine("A + B = " & C)
D=A-B
Console.WriteLine("A - B = " & D)
E=A*B
Console.WriteLine("A * B = " & E)
F=A/B
Console.WriteLine("A / B = " & F)
G=A\B
Console.WriteLine("A \ B = " & G)
If A > B Then
K=A^B
End If
Console.WriteLine("A ^ B = " & K)
Console.ReadLine()
End Sub
End Module
Output :
Enter two numbers
10
3
A + B = 13
A-B=7
A * B = 30
A/B=3
A\B=3
A ^ B = 1000
Selection Statements
Selection statements are statements that changes the flow of a program based on based on a
specific condition met or not.
This expression may be a relational expression or a logical expression which returns a boolean
value (true or false).
Visual Basic supports two types of selection statements
1. If…Else Statement
2. Select…Case Statement
1. If…Else Statement
The If…Else statement is used to test a condition satisfied or not. If it is yes the program control
is transferred to the blocks of code inside the If statement.
Otherwise, the program control is transferred to else block.
If Condition [Then]
[Block of Statements]
ElseIf condition [Then]
[Block of Statements]
Else
[Block of Statements]
End If
Dim a As Integer
Console.WriteLine("Enter a Number")
a = CInt(Console.ReadLine())
Console.WriteLine("Given Number = " & a)
If a > 0 Then
Console.Write("Positive Number")
ElseIf a < 0 Then
Console.Write("Negative Number")
Else
Console.Write("Number = 0")
End If
Console.ReadLine()
2. Select…Case
The Select…Case statements are used to compare value of expression, with different values or
other expressions in the given Case statements. If the case statement matches a specified
expression, the program control is transferred to that statement, as a result, the statements
inside that Case statements are executed.
Module Module1
Sub Main()
Dim ch As String
Console.WriteLine("Enter a Character")
ch = Console.ReadLine()
Console.WriteLine("Given Character = " & ch)
Select Case ch
Case "a"
Console.WriteLine("Vowel")
Case "e"
Console.WriteLine("Vowel")
Case "i"
Console.WriteLine("Vowel")
Case "o"
Console.WriteLine("Vowel")
Case "u"
Console.WriteLine("Vowel")
Case Else
Console.WriteLine("Not a Vowel")
End Select
Console.ReadLine()
End Sub
End Module
Module Module1
Sub Main()
Dim ch As String
Console.WriteLine("Enter a Character")
ch = Console.ReadLine()
Console.WriteLine("Given Character = " & ch)
Select Case ch
Case "a", "e", "i", "o", "u"
Console.WriteLine("Vowel")
Case Else
Console.WriteLine("Not a Vowel")
End Select
Console.ReadLine()
End Sub
End Module
Module Module1
Sub Main()
Dim i As Integer
Console.WriteLine("Enter a Character")
i = CInt(Console.ReadLine())
Select Case i
Case 1 To 10
Console.WriteLine("Number is between 1 & 10")
Case 11 To 20
Console.WriteLine("Number is between 11 & 20")
Case 30, 40, 50
Console.WriteLine("Number = 30 or 40 or 50")
Case Else
Console.WriteLine("Given Number = " & i)
End Select
Console.ReadLine()
End Sub
End Module
Iteration Statement
An Iteration statement executes a statement or set of statements repeatedly based on a
certain conditions. Iteration statements are also called loop statements.
Visual Basic 2010 Supports seven basic types of loop statements.
1. Entry Controlled Loops
a. The While…End While Statements
b. The Do While…Loop Statements
c. Do Until…Loop Statements
d. The For…Next Statements
e. The For Each…Statements
2. Exit Controlled Loops
a. Do…Loop While
b. Do…Loop Until
All types of loop contains 3 basic elements
Initialization Expression
Update Expression
Body of loop
1. While…End While Statements
The While…End While Statements continues to execute a set of statements as long as the given
condition is true. The while statement always checks the condition before executing the
statements within the loop, therefore it is called entry controlled loop. When the control
reaches the End While statement , the control is passed back to the While statement. If the
condition is becomes true, the statements within the loop are executed again & again;
otherwise , the loop exits.
The syntax of While statement is as follows:
While condition
[Statements]
End While
We can also terminate a while statements any time with an Exit While Statement.
Module Module1
Sub Main()
Dim i As Integer
While i <= 10
Console.WriteLine(i)
i=i+1
End While
Console.ReadLine()
End Sub
End Module
2. Do While…Loop Statements
The Do While…Loop statements is also used to execute a group of statements repeatedly.
The Do While…Loop statement executes a group of statements repeatedly as long as the
condition evaluates true. The Do While statement always checks the condition before executing
the statements within the loop, therefore it is called entry controlled loop.
When condition becomes false the loop terminates automatically.
Module Module1
Sub Main()
Dim i As Integer = 1
Do While i <= 10
Console.WriteLine(i)
i += 1
Loop
Console.ReadLine()
End Sub
End Module
3. Do Until…Loop
The Do Until…Loop statements is also used to execute a group of statements repeatedly.
The Do Until…Loop statement executes a group of statements repeatedly as long as the
condition evaluates false. The Do While statement always checks the condition before
executing the statements within the loop, therefore it is called entry controlled loop.
When condition becomes true the loop terminates automatically.
Do while condition
[Statements]
Loop
Module Module1
Sub Main()
Dim i As Integer
Do Until i > 10
Console.WriteLine(i)
i=i+1
Loop
Console.ReadLine()
End Sub
End Module
4. For…Next Statements
The For…Next Statement is used when we have to execute a group of statements repeatedly
for a specific number of times. The For…Next loop needs an index variable which counts the
no.of iterations. The counter variable automaticaly increment by one when looping through the
cycle.
Synatax :
For Variable = Start_Index To End_Index
[Statements]
[Exit For]
[Statements]
Next
Module Module1
Sub Main()
Dim i As Integer
For i = 1 To 10
Console.WriteLine(i)
Next
Console.ReadLine()
End Sub
End Module
Syntax :
For Each var_name As Type In Group
[Statements]
[Exit For]
Next
Module Module1
Sub Main()
Dim arr() As Integer = {1, 2, 3, 4, 5, 6}
For Each i As Integer In arr
Console.WriteLine(i)
Next
Console.ReadLine()
End Sub
End Module
Module Module1
Sub Main()
Dim i As Integer
Do
Console.WriteLine(i)
i=i+1
Loop While i <= 20
Console.ReadLine()
End Sub
End Module
Do
[Statements]
Loop Until condition
Module Module1
Sub Main()
Dim i As Integer
Do
Console.WriteLine(i)
i=i+1
Loop Until i = 20
Console.ReadLine()
End Sub
End Module
Sample Pgm
Program to find largest among two numbers
Module Module1
Sub Main()
Dim a As Integer, b As Integer
Console.WriteLine("Enter Two Numbers :")
a = CInt(Console.ReadLine())
b = CInt(Console.ReadLine())
If a > b Then
Console.WriteLine("Greater Number = " & a)
Else
Console.WriteLine("Greater Number = " & b)
End If
Console.ReadLine()
End Sub
End Module
Sample Pgm
Program to find largest among three numbers
Module Module1
Sub Main()
Dim a As Integer, b As Integer, c As Integer
Console.WriteLine("Enter 3 numbers")
a = CInt(Console.ReadLine())
b = CInt(Console.ReadLine())
c = CInt(Console.ReadLine())
If a > b Then
If a > c Then
Console.WriteLine("Largest Number = " & a)
Else
Console.WriteLine("Largest Number = " & c)
End If
Else
If b > c Then
Console.WriteLine("Largest Number = " & b)
Else
Console.WriteLine("Largest Number = " & c)
End If
End If
Console.ReadLine()
End Sub
End Module
Arrays
An array stores a fixed-size sequential collection of elements of the same type. An array as a
collection of variables of the same type. It is used to store a collection of data.
All arrays consist of continuous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
To declare an array in VB.Net, you use the Dim statement. Array elements can be accessed
using array index or bounce. While declaring an array, we uses its highest bounce (index) as
parameter. When we declare an array with bounce 4, actually it stores 5 elements , bcoz lowest
bounce starts from 0.
Sample Pgm
Program to demonstrate dynamic arrays.
Module Module1
Sub Main()
Dim arr() As Integer, i As Integer
ReDim arr(3)
Console.WriteLine("Enter Elements")
For i = 0 To 3
arr(i) = CInt(Console.ReadLine())
Next
Console.WriteLine("Elements are")
For Each vl As Integer In arr
Console.WriteLine(vl)
Next
ReDim arr(6)
Console.WriteLine("Enter Elements")
For i = 4 To 6
arr(i) = CInt(Console.ReadLine())
Next
Console.WriteLine("Elements are")
For Each vl As Integer In arr
Console.WriteLine(vl)
Next
Console.ReadLine()
End Sub
End Module
Sample Pgm
Program to demonstrate dynamic arrays using preserve keyword.
Module Module1
Sub Main()
Dim arr() As Integer, i As Integer
ReDim arr(3)
Console.WriteLine("Enter Elements")
For i = 0 To 3
arr(i) = CInt(Console.ReadLine())
Next
Console.WriteLine("Elements are")
For Each vl As Integer In arr
Console.WriteLine(vl)
Next
ReDim Preserve arr(6)
Console.WriteLine("Enter Elements")
For i = 4 To 6
arr(i) = CInt(Console.ReadLine())
Next
Console.WriteLine("Elements are")
For Each vl As Integer In arr
Console.WriteLine(vl)
Next
Console.ReadLine()
End Sub
End Module
Object
Any entity that has state and behavior is known
as an object. It can be physical or logical.
An Object can be defined as an instance of a
class. Both data and function that operate on
data are bundled as a single unit, called as object.
Anything that we see around us can be treated as
an object and all these objects have properties
(also called member/data/state) and
behaviour (also called
methods/member functions).
Class
Simply a class is called collection of
objects. An object is defined via its
class which determines everything
about an object. A class is a
prototype/blue print that defines the
specification common to all objects of
a particular type. This specification
contains the details of the data and
functions that act upon the data.
Objects of the class are called
individual instances of the class and
any number of objects can be created based on a class.
Inheritance
One of the most useful aspects of object-oriented programming is code reusability. As the
name suggests Inheritance is the process of forming a new class from an existing class that is
class called as base class, new class is formed called as derived class.
This is a very important concept of object-oriented programming since this feature helps to
reduce the code size.
Polymorphism
'Poly' means many. 'Morph' means shapes. So polymorphism can be defined as the ability to
express different forms. This is demonstrated in Figure . Here the same command "Now Speak"
is issued to all objects, but each object
responds differently to the same command.
Abstraction
Data abstraction refers to, providing only essential information to the outside world and hiding
their background details, i.e., to represent the needed information in program without
presenting the details.
Let us take a real life example of a television which we can turn on and off, change the channel,
adjust the volume, and add external components such as speakers, VCRs, and DVD players, but
we do not know about its internal details, that is, we do not know how it receives signals over
the air or through a cable, how it translates them, and finally displays them on the screen.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
All C++ programs are composed of two fundamental elements, functions and data.
Encapsulation is an OOP concept that binds together the data and functions that manipulate
the data, and keeps both data and function safe from outside interference and misuse.
The best way to understand encapsulation is to look at the example of a medical capsule,
where the drug is always safe inside the capsule. Similarly, through encapsulation the methods
and variables of a class are well hidden and safe.
Sub main()
displaymsg()
Console.ReadLine()
End Sub
Sub displaymsg()
Console.WriteLine(“Welcome”)
End Sub
The parameter mentioned here means that, the values or variables that are passed to sub
procedure or a function, they are also called arguments.
We can pass values into sub procedure by 2 ways.
1. Pass By Value
In the pass by value method, a separate copy of variable is passed to the sub procedure. If
we makes any changes to the value passed into sub procedure, it willnot affect the value in
the original copy. VB uses ByVal Keyword when a value is passed to a sub procedure.
Sub Display(ByVal str As String)
Console.writeLine(str)
Console.Readline()
End Sub
Module Module3
Sub Main()
Dim C As Integer
Console.WriteLine("Enter a Number")
C = CInt(Console.ReadLine())
display(C)
Console.WriteLine("C = " & C & " From Sub Main Procedure")
Console.ReadLine()
End Sub
Sub display(ByVal C As Integer)
C = C + 20
Console.WriteLine("C = " & C & " From Sub Procedure")
End Sub
End Module
OutPut :
Enter a Number
70
C = 90 From Sub Procedure
C = 70 From Main Procedure
2. Pass By Reference
When you pass an argument by Pass by reference method, the location of the variable is
passed to the sub procedure. This implies that we have direct access to that variable. That
means , Changing the value of an argument in sub procedure also changes the value in its
original copy.
Sub Display(ByRef str As String)
Console.writeLine(str)
Console.Readline()
End Sub
Module Module3
Sub Main()
Dim C As Integer
Console.WriteLine("Enter a Number")
C = CInt(Console.ReadLine())
display(C)
Console.WriteLine("C = " & C & " From Sub Main Procedure")
Console.ReadLine()
End Sub
Sub display(ByRef C As Integer)
C = C + 20
Console.WriteLine("C = " & C & " From Sub Procedure")
End Sub
End Module
OutPut :
Enter a Number
40
C = 60 From Sub Procedure
C = 60 From Main Procedure
Functions
Functions are similar to sub procedures, except the difference is that a function can return
values. The syntax for creation of function is shown below :
Function Function_name(Parameters) As Return_Type
Statements
Return Statement
End Function
A function can be created using the keyword Function. Followed by Function_name. The
parameters here refers to the list of values which are passed to the function. The
values/Variables can be passed to function using PassBy value or PassBy Methods.
Function has a return statement which denotes which type & value is returned after executing
the function.
Module Module2
Function addition(ByVal a As Integer, ByVal b As Integer) As Integer
Dim sum As Integer
sum = a + b
Return sum
End Function
Sub Main()
Dim sum As Integer
sum = addition(15, 25)
Console.WriteLine("Sum = " & sum)
Console.ReadLine()
End Sub
End Module
Module Module1
Public Class students
Dim rgn As Integer, name As String
Public Sub New() ‘Constructor without parameters
Console.WriteLine("Enter Reg Num & Name")
rgn = CInt(Console.ReadLine())
name = Console.ReadLine()
End Sub
Public Sub New(ByVal n As Integer, ByVal nm As String)
‘Constructor with parameter
rgn = n
name = nm
End Sub
Sub display()
Console.WriteLine("Register Number : " & rgn)
Console.WriteLine("Name : " & name)
End Sub
End Class
Sub Main()
Dim obj1 As students = New students()
Dim obj2 As students = New students(2, "Abhi")
Dim obj3 As students = New students(3, "Arun")
obj1.display()
obj2.display()
obj3.display()
Console.ReadLine()
End Sub
End Module
When can create an array of objects, which means we can create any no.of objects of a same
class by using Arrays.
Module Module1
Class student
Private regno As Integer
Private name As String
Private phno As Long
Private marks As Double
Public Sub New()
Console.WriteLine(Constants.vbLf & "Enter Registration
Number")
regno = CInt(Console.ReadLine())
Console.WriteLine("Enter Name")
name = Console.ReadLine()
Console.WriteLine("Enter Phone Number" & Constants.vbLf)
phno = CLng(Console.ReadLine())
Console.WriteLine("Enter Marks")
marks = CDbl(Console.ReadLine())
End Sub
Public Sub display()
Console.WriteLine("Registration Number : " & regno)
Console.WriteLine("Name : " & name)
Console.WriteLine("Phone Number : " & phno)
Console.WriteLine("Marks obtained : " & marks)
End Sub
End Class
Sub Main()
Dim obj(3) As student
For i = 0 To 3
Console.WriteLine("Enter datas of student " & i + 1)
obj(i) = New student()
Next
For i = 0 To 3
Console.WriteLine("Datas of student " & i + 1)
obj(i).display()
Next
Console.ReadLine()
End Sub
End Module
Partial Classes
In VB , a partial class is the class that enables you to specify the definition of a class in two or
more source files. All the source file contain a section of the class definition. The definitions in
the different source files are combined when the application is executed. We can divide a class
into 2 or more partial classes each stored in separate files , so that we can work on each partial
class seperately. We can declare a partial class by using the Partial keyword. The partial
keyword indicates that all the parts of the class must be available at compile time to generate
the final class.
Module Module1
Partial Public Class sample 'Partial Class Definition 1
Public x As Integer
Public y As Integer
Public Sub New(ByVal p As Integer, ByVal q As Integer)
x = p
y = q
End Sub
End Class
Partial Public Class sample 'Partial Class Definition 2
Public Sub display()
Console.WriteLine("a = " & x)
Console.WriteLine("b = " & y)
End Sub
End Class
Sub Main()
Dim obj As sample = New sample(29, 25)
obj.display()
Console.ReadLine()
End Sub
End Module
Shared Methods
A shared method refers a method that is directly accessed without creating an instance of the
class in which it is declared. We can use the class name and the dot operator (.) to access a
shared method outside the class.
Module Module1
Public Class MathAddition
Public Shared Sub addition(ByVal a As Integer, ByVal b As
Integer)
Console.WriteLine("Sum = " & a + b)
End Sub
End Class
Sub Main()
MathAddition.addition(10, 20)
MathAddition.addition(15, 25)
Console.ReadLine()
End Sub
End Module
Extensions Methods
An extension method is one of the new features in Visual Basic 2010. It is a technique used to
extend a class from that class. The behaviour of extension methods is similar to that of shared
methods. An extension methods can be either a function or a sub procedure.
To define a method as an extension method , you must mark the method with extension
attribute, <Extension()> , which belongs to the System.Runtime.CompilerServices namespace.
Imports System.Runtime.CompilerServices
Module Module1
<Extension()>
Public Sub display()
Console.WriteLine("Welcome to my program")
End Sub
End Module
In the above example, we created a sub procedure display(), which marked as <Extension()>. To
use an extension attribute we must import System.Runtime.CompilerServices namespace.
Extension methods can be declared only within modules. The module, in which an extension
method defined, is not the same module as one in which it is called.
Imports ConsoleApplication39.Module1
Module Module2
Sub Main()
display("Welcome to my program")
Console.ReadLine()
End Sub
End Module
For calling this extension method, we added a new module Module2, & then import the
previous module as shown below.
Imports Project_Name.Module_Name
Encapsulation
Encapsulation is the process of hiding the irrelevent information and showing only the relevent
information to a user. It is away to organize data and methods to a single unit ; thereby,
preventing the data from being modified by unauthorized users. Encapsulation is implemented
through access modifiers. Access modifiers help to improve the this feature by defining a scope
to access data and methods in a restricted manner.
Consequently, you can describe encapsulation as the ability of an object to hide its internal data
and methods and to make only the intended parts programmatically accessible.
In terms of OOP, encapsulation is the process of wrapping data and members in a class. Only
specific methods or properties can access the private members of a class. In other words,
encapsulation is an approach to hide the internal state and behaviour of a class or an object
from unauthorized access. It restricts the external users sharing and manipulating data.
The advantages of encapsulation are as follows:
Data hiding through the use of the private access modifiers
Increasing the maintainability of the code
Preventing data corruption
Wrapping up of data members & member functions
Module Module1
Class class1
Private x As Integer = 20
Public y As Integer = 30
Protected z As Integer = 90
Public Sub display()
Console.WriteLine("X = " & x)
Console.WriteLine("Y = " & y)
Console.WriteLine("Z = " & z)
End Sub
End Class
Sub Main()
Dim obj As class1 = New class1()
Console.WriteLine("Y = " & obj.y)
obj.display()
Console.ReadLine()
End Sub
End Module
All the class members are accessible except the private members . Private members are only
accessible in the class in which they are declared.
Protected members are accessible from either the class in ehich they are declared or a class
derived from the class in which they are declared.
Inheritance
inheritance is defined as the property through which a child class obtains all features defined in
its parent class. A parent class is the higher level in the class hierarchy as compared to the child
class. Inheritance represents a kind of relationship between two classes.
For Eg: consider the parrot as a child class, it obtains all features from the parent class, the bird
class.
When a class inherits the properties of another class, the class inheriting the properties is called
a derived class and the class that allows inheritance of its properties is called a base class.
Inheritance in OOP is of 4 Types :
1. Single inheritance :
Contains one base class & one derived class
2. Hierarchical inheritance :
Contains one base class and multiple derived classes of the same base class
3. Multilevel inheritance :
Contains a class derived from another derived class
4. Multiple Inheritance :
Contains several base classes and a derived class
A derived class inherits all the non-private data of its base class. It also inherits the behaviour of
the base class.
Defining a derived Class
We uses keyword Inherits to inherit properties from a Base Class.
Accessing Members of the Base Class
When a class is derived from a base class, the members of the base class becomes members of
the derived class. We can access those variable using object of derived class & dot operator (.).
Module Module1
Public Class classA 'Base Class
Public a As Integer = 10
Protected b As Integer = 20
Private c As Integer = 30
Public Sub display()
Console.WriteLine("Hii Welcome")
Console.WriteLine("Private Variable : " & c)
Console.WriteLine("Protected Variable : " & b)
End Sub
End Class
Public Class classB 'Derived Class
Inherits classA 'Inherited from ClassA
Public Sub show()
Console.WriteLine("Protected Variable : " & b)
End Sub
End Class
Sub main()
Dim obj2 As classB = New classB()
Console.WriteLine("Accessing Members of Base Class From
Derived Class")
obj2.display()
Console.WriteLine("Public Variable : " & obj2.a)
obj2.show()
Console.ReadLine()
End Sub
End Module
Abstract Classes
Abstract classes are that contains only the declaration of a method; whereas, the method is
defined in the class derived from the abstract class. In other words abstract classes are similar
to the base classes except that the methods are declared inside the abstract classes, known as
abstract methods, they do not have method bodies. If you have created a base class and want
to ensure that no object of the base class is created later, we can make the base class as
abstract. The MustInherit keyword in a class indicates that the class cannot be instantiated and
is an abstract class. The basic purpose of abstract class is to provide a common definition of the
base class that can be shared by multiple derived classes.
Characteristics of an abstract class are given below:
We cannot instantiate an abstract class directly. This implies that you cannot create an
object of the abstract class. To use members of an abstract class, you need to define a
non-abstract class that inherits the abstract class. After you have defined the non
abstract classes, you can access the members of the abstract class using the object of
the non abstract classes.
An abstract class can contain abstract as well as non-abstract members
You must declare at least one abstract method in a abstract class
An abstract class is always public
Module Module1
Public MustInherit Class areaofshape
Public a As Double = 12
Public MustOverride Function area() As Double
End Class
Public Class circle
Inherits areaofshape
Public Overrides Function area() As Double
Dim ar As Double
ar = 3.14 * a * a
Return ar
End Function
End Class
Public Class square
Inherits areaofshape
Public Overrides Function area() As Double
Dim ar As Double
ar = a * a
Return ar
End Function
End Class
Sub Main()
Dim obj1, obj2 As areaofshape
obj1 = New circle()
obj2 = New square()
Console.WriteLine("Area of Circle = " & obj1.area())
Console.WriteLine("Area of square = " & obj2.area())
Console.ReadLine()
End Sub
End Module
Sealed Classes
A sealed class implies that the class cannot be used as a base class. You can declare a class as
sealed, if you want to prevent other users to derive a class from that class. Once you have
declared as sealed, no other class can inherit that class. The NotInheritable keyword is used to
indicate that a class cannot be inherited. When we apply the NotInheritable keyword as a
modifier to a class, it will become final.
Module module1
NotInheritable Class sealedclass
Public Sub display()
Console.WriteLine("Hello Everyone")
End Sub
End Class
Sub Main()
Dim obj As sealedclass = New sealedclass()
obj.display()
Console.ReadLine()
End Sub
End Module
Polymorphism
polymorphism means one name many forms. Using this feature of polymorphism, you can use
one method in many ways based on your requirements.
For example, you can write a method to calculate the area of a geometrical figure and use the
same method to calculate area of circle, triangle, or rectangle using different values & types of
parameters.
Polymorphism is of two types
1. Compile Time Polymorphism
2. Run Time Polymorphism
Compile Time Polymorphism
When a compiler compiles compiles a program, the compiler has the information about the
method arguments. Accordingly, the compiler finds the appropriate method to the respective
object at the compile time itself. This process is called compile time polymorphism or early
binding. We can implement compile time polymorphism through overloaded methods and
operators. The arguments passed to overloaded methods are matched interms of number,
type, and order; and then the overloaded methods are invoked.
Compile time polymorphism can be implemented In two ways
1. Method Overloading
2. Operator Overloading
Method Overloading
Method overloading is a concept in which a method in which a method behaves according to
the number and types of parameters passed to it. It allows you to define multiple methods with
the same name but with different signatures. When you call overloaded methods, the compilor
automatically determines which method should be used according to the signature specified in
the method call.
Module Module1
Public Class shape
Public Sub area(ByVal side As Integer)
Dim area As Integer = side * side
Console.WriteLine("Area of Square : " & area)
End Sub
Public Sub area(ByVal length As Integer, ByVal breadth As Integer)
Dim area As Integer = length * breadth
Console.WriteLine("Area of rectangle : " & area)
End Sub
Public Sub area(ByVal rad As Double)
Dim area As Double = 3.14 * rad * rad
Console.WriteLine("Area of Circle : " & area)
End Sub
End Class
Sub Main()
Dim obj As shape = New shape()
obj.area(25)
obj.area(10, 20)
obj.area(10.0)
Console.ReadLine()
End Sub
End Module
Creating a structure
A structure in VB is a user defined value type. It is used to store values of different data types.
Similar to class, it can contain constructors, fields, methods and nested types. We can use the
structure statement to create a structure. All elements of a structure are private by default. In
VB major difference between structure & class is that a structure does not support inheritance.
The syntax of a structure declaration is given below:
<attributelist> <accessmodifier> Structure Structure_Name
[Implements Interfacenames]
Data Member Declarations
[method declarations]
End Structure
Module module1
Public Structure sample
Public x As Integer
Public y As Integer
Public z As Integer
End Structure
Sub Main()
Dim v1 As sample
v1.x = 10
v1.y = 20
v1.z = 30
Console.WriteLine("X = {0} Y = {1} Z = {2}", v1.x, v1.y, v1.z)
Dim v2 As sample = New sample()
Console.WriteLine("X = {0} Y = {1} Z = {2}", v2.x, v2.y, v2.z)
Console.ReadLine()
End Sub
End Module
Properties
A property provides you a way to expose an internal element (Private Variable) of a class in a
simple and intuitive manner. We can create a property by defining an externally available
name. The Get & Set property procedures are used to implement the property. The Get
property procedure is used to return the property value and the Set property procedure is used
to assign a new value to the property.
Module Module1
Public Class EmployeeDetail
Private empname As String
Public Property Name() As String
Get
Return empname
End Get
Set(ByVal value As String)
empname = value
End Set
End Property
End Class
Sub Main()
Dim emp1 As EmployeeDetail = New EmployeeDetail()
emp1.Name = "Neelima Agarwal"
Console.WriteLine("Employee Name = {0}", emp1.Name)
Console.ReadLine()
End Sub
End Module
Module Module1
Property Name As String = "Neelima"
Property Age As Integer = 26
Sub Main()
Console.WriteLine(Name)
Console.WriteLine(Age)
Console.ReadLine()
End Sub
End Module
Using Interfaces
An interface is a collection of abstract data members and member functions. Interfaces in visual
basic are introduced to provide the feature of multiple inheritance to classes. The method
defined in an interface do not have their implementation. They only specify the number & types
of parameters they will take and the type of values they will return. An interface is always
implemented by a class. In VB an interface is equivalent to abstract base class. You cannot
instantiate an object through an interface. But you can offer a set of functionalities that is
common to several different classes.
Defining an interface
Similar to defining a class, we can define an interface. The difference is that a class is defined
with the Class keyword and an interface is defined with Interface keyword. The syntax to define
an interface is shown below
Interface InterfaceName
'Abstract Method Declarations in Interface Body
End Interface
You can use the Implements keyword to implement an interface.
A Windows forms application is one that runs on the desktop computer. A Windows forms
application will normally have a collection of controls such as labels, textboxes, list boxes, etc.
Below is an example of a simple Windows form application. It shows a simple Login screen,
which is accessible by the user. The user will enter the required credentials and then will click
the Login button to proceed.
1. Editor Window or
1 Main Window 2 3
2. Solution Explorer
Window
3. Properties Window
Editor Window or Main Window: Here, you will work with forms and code editing. You can
notice the layout of form which is now blank. You will double click the form then it will open the
code for that.
Solution Explorer Window: It is used to navigate between all items in solution. For example, if
you will select a file form this window then particular information will be display in the property
window. (Right Side, Ctrl + R)
Properties Window: This window is used to change the different properties of the selected
item in the Solution Explorer. Also, you can change the properties of components or controls
that you will add to the forms. (Right Side, F4)
You can also reset the window layout by setting it to default. To set the default layout, go to
Window -> Reset Window Layout in Visual Studio Menu.
Title Bar, Toolbar, and Menu Bar
The Title bar displays the application name and the name of the active data file (or untitled if no
data file is associated with the data being displayed).
The Menu bar displays the available menus and commands.
The Toolbar contains buttons for frequently-used commands.
Manual Sets initial position of the form according to the value of Location
property
CenterScreen Positions the form at the center of the screen & sets the dimensions
of the form according to the value of the size property of the form
WindowsDefaultLocation Positions the form at the windows default location and sets the
dimensions of the form according to the value of its Size property.
This is the default value for the StartPosition property of a form
WindowsDefaultBounds Positions the form at the windows default location and sets its
dimensions according to the default settings of windows (Operating
System)
CenterParent Positions the form as centered within the bounds of its parent form
In some situation, you may also require to display a form in a fixed state, such as Normal,
Minimized, or Maximized. In such situation, you can set the initial state of the form by setting
its Windowstate property at either design or run time. The Windowstate property can be set to
any of the following values.
Normal : sets the state of the form to the restored state. This is the default value for
the Windowstate property
Minimized : Sets the state of the form to minimized and as a result, the form appears
on taskbar
Maximized : Sets the state of the form to maximized and as a result it covers entire
area
Button Control
A button is used to allow the user to click on a button which would then start the processing of
the form.
Also used to rise up an event or a method.
Properties
Name
Anchor
BackColor
BackgroundImage
Dock
Enabled
Font
ForeColor
Size
TabIndex
Text
TextAlign
Visible
Docking refers to attaching a control either to an edge (top, right, bottom or left) or the client
area of the parent control.
On the other hand, in anchoring, you specify the distance that each edge of your control
maintains from the edges of parent control.
You can set the Dock property of a control to arrange them accordingly.
You can set the Anchor property of a control for anchoring purpose.
You can make a control visible or invisible at run time. Each control has a property, named
Visible, which you can use to show or hide the control.
Controls on a form can be made accessible in an appropriate sequence by setting their
TabIndex property.
We can change the order of focusing while pressing Tab Key, by changing the TabIndex
property of a form control.
You can disable a form control element using its Enable property in the properties window. You
can set it to False if you want to disable it.
Or we can use the code to disable a form control element.
Checkbox
A checkbox is used to provide a list of options in which the user can choose multiple choices.
Properties
Name
Anchor
BackColor
BackgroundImage
CheckAlign
Checked
Dock
Enabled
Font
Forecolour
Size
TabIndex
Text
TextAlign
visible
Checked List
Contains multiple checkbox items in a list
Properties
Name
Anchor
BackColor
Dock
Enabled
Font
ForeColor
Items (Collections)
Size
TabIndex
Visible
ComboBox
Displays an editable text box with a drop-down list of permitted values.
Properties
Name
Anchor
BackColor
CheckAlign
Dock
DropDownHeight
DropDownStyle
DropDownWidth
Enabled
Font
Forecolour
Items (Collection)
MaxLength
Size
TabIndex
Text
Visible
DateTimePicker
Enables the user to select a date and time, and to display that date and time in a specified
format.
Properties
Format
Anchor
Font
MinDate
MaxDate
Size
TabIndex
Value
Label
Provides run time information or a descriptive text for a control.
Properties
Font
FontColor
Text
Enabled
Anchor
Dock
Visible
LinkLabel
Displays a label control that supports hyperlink functionality, formatting & tracking.
Properties
Textbox
A textbox is used for allowing a user to enter some text on the forms application.
Properties
List box
A List box is used to showcase a list of items on the Windows form.
Radio Button
A Radio button is used to showcase a list of items out of which the user can choose one.
Group Box
A group box is used for logical grouping controls into a section. GroupBox has a particular name
for that area, to categorize groups.
Panel
A Panel is used for logical grouping controls into a section. Panel has no particular name for that
area, we can create group of similar controls together without providing any name.
We can choose these two events using two buttons. One for accept button & other for Cancel
button.
Module Module1
Sub Main()
MsgBox("Displays a message as MsgBox()")
End Sub
End Module
Cancel 2
Abort 3
Retry 4
Ignore 5
Yes 6
No 7
Integral
To Display MsgBoxStyle
Value
OKOnly 0
OKCancel 1
AbortRetryIgnore 2
YesNoCancel 3
YesNo 4
RetryCancel 5
Critical 16
Question 32
Exclamation 48
Information 64
Event Description
MouseDown Occurs when the mouse pointer is over the control and a mouse button is
pressed
MouseEnter Occurs when the mouse pointer enters the control region
MouseHover Occurs when the mouse pointer moves over the control region
Occurs when the mouse pointer leaves the control region
MouseMove Occurs when the mouse pointer moves over the control
MouseUp Occurs when the cursor of the mouse is placed on a control and the left
mouse button is released
MouseWheel Occurs when a control has focus and the wheel of the mouse moves
Events Description
KeyDown Occurs when a key is pressed down while the control has focus
KeyPress Occurs when a key is pressed while the control has focus
KeyUp Occurs when a key is released while the control has focus
MenuStrip
Displays application commands & options grouped by functionality.
Simple Calculator
LINQ queries return results as objects. It enables you to uses object-oriented approach on the
result set and not to worry about transforming different formats of results into objects.
LINQ to Objects: The LINQ to Objects provider enables you to query in-memory
collections and arrays.
LINQ to DataSet: The LINQ to DataSet provider enables you to query and update data in
an ADO.NET dataset.
LINQ to XML: The LINQ to XML provider enables you to query and modify XML. You can
modify in-memory XML, or you can load XML from and save XML to a file.
LINQ to SQL: The LINQ to SQL provider enables you to query and modify data in a SQL
Server database. This makes it easy to map the object model for an application to the
tables and objects in a database.
Example:
Distinct clause
Optional. A Distinct clause restricts the values of the current iteration variable to
eliminate duplicate values in query results.