0% found this document useful (0 votes)
7 views

Notes

Uploaded by

abhishek
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Notes

Uploaded by

abhishek
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Introduction to .

NET Framework
The .NET Framework is a software development platform that was introduced by
Microsoft in the late 1990. On 13 February 2002, Microsoft launched the first version of
the .NET Framework, referred to as the .NET Framework 1.0.

What is .NET Framework?

It is a virtual machine that provide a common platform to run an application that was built
using the different language such as C#, VB.NET, Visual Basic, etc. It is also used to
create a form based, console-based, mobile and web-based application or services that
are available in Microsoft environment. Furthermore, the .NET framework is a pure
object oriented, that similar to the Java language. But it is not a platform independent as
the Java. So, its application runs only to the windows platform.

The main objective of this framework is to develop an application that can run on
the windows platform. The current version of the .Net framework is 4.8.

Note: The .NET Framework is not only a language, but it is also a software and
language neutral platform.

Components of .NET Framework


There are following components of .NET Framework:

1. CLR (Common Language Runtime)


2. CTS (Common Type System)
3. BCL (Base Class Library)
4. CLS (Common Language Specification)
5. FCL (Framework Class Library)
6. .NET Assemblies
7. XML Web Services
8. Window Services

CLR (common language runtime)

It is an important part of a .NET framework that works like a virtual component of the
.NET Framework to executes the different languages program like C#, Visual Basic, etc.
A CLR also helps to convert a source code into the byte code, and this byte code is known
as CIL (Common Intermediate Language) or MSIL (Microsoft Intermediate Language).
After converting into a byte code, a CLR uses a JIT compiler at run time that helps to
convert a CIL or MSIL code into the machine or native code.

What is Just-In-Time(JIT) Compiler in .NET


Just-In-Time compiler(JIT) is a part of Common Language Runtime
(CLR) in .NET which is responsible for managing the execution of .NET programs
regardless of any .NET programming language. A language-specific compiler converts
the source code to the intermediate language. This intermediate language is then
converted into the machine code by the Just-In-Time (JIT) compiler. This machine code
is specific to the computer environment that the JIT compiler runs on.

Working of JIT Compiler:

The JIT compiler is required to speed up the code execution and provide support for
multiple platforms. Its working is given as follows:
The JIT compiler converts the Microsoft Intermediate Language (MSIL) or Common
Intermediate Language(CIL) into the machine code. This is done before the MSIL or CIL
can be executed. The MSIL is converted into machine code on a requirement basis i.e.
the JIT compiler compiles the MSIL or CIL as required rather than the whole of it. The
compiled MSIL or CIL is stored so that it is available for subsequent calls if required.
Types of Just-In-Time Compiler: There are three types of JIT compilers which are as
follows:

1. Pre-JIT Compiler: All the source code is compiled into the machine code at the
same time in a single compilation cycle using the Pre-JIT Compiler. This
compilation process is performed at application deployment time. And this compiler
is always implemented in the Ngen.exe (Native Image Generator).
2. Normal JIT Compiler: The source code methods that are required at run-time are
compiled into machine code the first time they are called by the Normal JIT
Compiler. After that, they are stored in the cache and used whenever they are called
again.
3. Econo JIT Compiler: The source code methods that are required at run-time are
compiled into machine code by the Econo JIT Compiler. After these methods are
not required anymore, they are removed.

CTS (Common Type System)

It specifies a standard that represent what type of data and value can be defined and
managed in computer memory at runtime. A CTS ensures that programming data defined
in various languages should beinteract with each other to share information. For example,
in C# we define data type as int, while in VB.NET we define integer as a data type.
BCL (Base Class Library)

The base class library has a rich collection of libraries features and functions that help to
implement many programming languages in the .NET Framework, such as C #, F #,
Visual C ++, and more. Furthermore, BCL divides into two parts:

1. User defined class library


o Assemblies - It is the collection of small parts of deployment an
application's part. It contains either the DLL (Dynamic Link Library) or exe
(Executable) file.
1. In LL, it uses code reusability, whereas in exe it contains only output
file/ or application.
2. DLL file can't be open, whereas exe file can be open.
3. DLL file can't be run individually, whereas in exe, it can run
individually.
4. In DLL file, there is no main method, whereas exe file has main
method.
2. Predefined class library
o Namespace - It is the collection of predefined class and method that present
in .Net. In other languages such as, C we used header files, in java we used
package similarly we used "using system" in .NET, where using is a
keyword and system is a namespace.

CLS (Common language Specification)

It is a subset of common type system (CTS) that defines a set of rules and regulations
which should be followed by every language that comes under the .net framework. In
other words, a CLS language should be cross-language integration or interoperability.
For example, in C# and VB.NET language, the C# language terminate each statement
with semicolon, whereas in VB.NET it is not end with semicolon, and when these
statements execute in .NET Framework, it provides a common platform to interact and
share information with each other.

Microsoft .NET Assemblies

A .NET assembly is the main building block of the .NET Framework. It is a small unit of
code that contains a logical compiled code in the Common Language infrastructure (CLI),
which is used for deployment, security and versioning. It defines in two parts (process)
DLL and library (exe) assemblies. When the .NET program is compiled, it generates a
metadata with Microsoft Intermediate Language, which is stored in a file called
Assembly.
FCL (Framework Class Library)

It provides the various system functionality in the .NET Framework, that includes classes,
interfaces and data types, etc. to create multiple functions and different types of
application such as desktop, web, mobile application, etc. In other words, it can be
defined as, it provides a base on which various applications, controls and components are
built in .NET Framework.

Key Components of FCL

1. Object type
2. Implementation of data structure
3. Base data types
4. Garbage collection
5. Security and database connectivity
6. Creating common platform for window and web-based application

Characteristics of .NET Framework


1. CLR (Common Language Runtime)
2. Namespace - Predefined class and function
3. Metadata and Assemblies
4. Application domains
5. It helps to configure and deploy the .net application
6. It provides form and web-based services
7. LINQ (Language Integrated Query - LINQ belongs to System.Linq namespace.
LINQ allows you to write structured and type safe queries. It allows you to query
local data as well as remote data.)
8. Security and Portability
9. Interoperability
10.It provides multiple environments for developing an application

Versions of .NET Framework

1. On 13 February 2002, Microsoft launched first version of .Net framework 1.0.


2. The second version 2.0 of .net framework was launched on 22 January 2006.
3. Third version 3.0 of .Net framework was released on 21 November 2006.
4. A .Net framework version 3.5 was released on 19 November 2007.
5. Version 4.0 of .Net framework was released on 29 September 2008
6. Version 4.5 of .Net framework was released on 15 August 2012.
7. .Net framework 4.5.1 version was announced on 17 October 2013
8. On 5 May 2014, a 4.5.2 version of .Net framework was released.
9. .Net framework 4.6 version was announced on 12 November 2014
10..Net framework 4.6.1 version was released on 30 October 2015
11..Net framework 4.6.2 version was announced on March 30, 2016
12..Net framework 4.7 version was announced on April 5, 2017
13..Net framework 4.7.1 version was announced on October 17, 2017
14.Version 4.7.2 of .Net framework was released on 30 April 2018.
15.And currently we are using .Net framework version 4.8 that was released on 18
April 2019
Introduction to VB.NET
Visual Basic .NET (VB.NET) is an object-oriented computer programming language
implemented on the .NET Framework. it is an evolution of classic Visual Basic
language, it is not backwards-compatible with VB6, and any code written in the old
version does not compile under VB.NET.

Like all other .NET languages, VB.NET has complete support for object-oriented
concepts. Everything in VB.NET is an object, including all of the primitive types (Short,
Integer, Long, String, Boolean, etc.) and user-defined types, events, and even
assemblies. All objects inherits from the base class Object.

VB.NET is implemented by Microsoft's .NET framework. Therefore, it has full access


to all the libraries in the .Net Framework. The following reasons make VB.Net a widely
used professional language –

• Modern, general purpose.


• Object oriented.
• Component oriented.
• Easy to learn.
• Structured language.
• It produces efficient programs.
• It can be compiled on a variety of computer platforms.
• Part of .Net Framework.

Strong Programming Features VB.Net


• Boolean Conditions
• Automatic Garbage Collection
• Standard Library
• Assembly Versioning
• Properties and Events
• Delegates and Events Management
• Easy-to-use Generics
• Indexers
• Conditional Compilation
• Simple Multithreading
Integrated Development Environment (IDE) For VB.Net

Microsoft provides the following development tools for VB.Net programming −


• Visual Studio (VS)
• Visual Basic Express (VBE)
• Visual Web Developer

The last two are free. Using these tools, you can write all kinds of VB.Net programs
from simple command-line applications to more complex applications. Visual Basic
Express and Visual Web Developer Express edition are trimmed down versions of
Visual Studio and has the same look and feel. They retain most features of Visual Studio.

Although the.NET Framework runs on the Windows operating system, there are some
alternative versions that work on other operating systems. Mono is an open-source
version of the .NET Framework which includes a Visual Basic compiler and runs on
several operating systems, including Linux and Mac OS. The most recent version is VB
2019.

The stated purpose of Mono is not only to be able to run Microsoft .NET applications
cross-platform, but also to bring better development tools to Linux developers. Mono
can be run on many operating systems including Android, BSD, iOS, Linux, OS X,
Windows, Solaris and UNIX.

Structure of VB.Net program

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

WAP to print the words "Hello World" −


Imports System
Module Module1
'This program will display Hello World
Sub Main()
Console.WriteLine("Hello World")
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result –

Hello, World!

Various parts of the above program –

• The first line of the program Imports System is used to include the System
namespace in the program.

• The next line has a Module declaration, the module Module1. VB.Net is
completely object oriented, so every program must contain a module of a class
that contains the data and procedures that your program uses.

• Classes or Modules generally would contain more than one procedure. Procedures
contain the executable code, or in other words, they define the behaviour of the
class. A procedure could be any of the following −
o Function
o Sub
o Operator
o Get
o Set
o AddHandler
o RemoveHandler
o RaiseEvent

• The next line( 'This program) will be ignored by the compiler and it has been put
to add additional comments in the program.

• The next line defines the Main procedure, which is the entry point for all VB.Net
programs. The Main procedure states what the module or class will do when
executed.

• The Main procedure specifies its behaviour with the statement


Console.WriteLine("Hello World") WriteLine is a method of the Console class
defined in the System namespace. This statement causes the message "Hello,
World!" to be displayed on the screen.

•The last line Console.ReadKey() is for the VS.NET Users. This will prevent the
screen from running and closing quickly when the program is launched from
Visual Studio .NET.
Compile & Execute VB.Net Program
If you are using Visual Studio.Net IDE, take the following steps −
• Start Visual Studio.
• On the menu bar, choose File → New → Project.
• Choose Visual Basic from templates
• Choose Console Application.
• Specify a name and location for your project using the Browse button, and then
choose the OK button.
• The new project appears in Solution Explorer.
• Write code in the Code Editor.
• Click the Run button or the F5 key to run the project. A Command Prompt window
appears that contains the line Hello World.

You can compile a VB.Net program by using the command line instead of the
Visual Studio IDE –

• Open a text editor and add the above mentioned code.


• Save the file as helloworld.vb
• Open the command prompt tool and go to the directory where you saved the file.
• Type vbc helloworld.vb and press enter to compile your code.
• If there are no errors in your code the command prompt will take you to the next
line and would generate helloworld.exe executable file.
• Next, type helloworld to execute your program.
• You will be able to see "Hello World" printed on the screen.
Introduction to VB.NET
Identifiers
An identifier is a name used to identify a class, variable, function, or any other user-
defined item. The basic rules for naming classes in VB.Net are as follows –

• A name must begin with a letter that could be followed by a sequence of letters,
digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.

• It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ]


{ } . ; : " ' / and \. However, an underscore ( _ ) can be used.

• It should not be a reserved keyword.

• It should not more than 51 characters.

VB.Net Keywords
A keyword is a reserved word with special meanings in the compiler, whose meaning
cannot be changed. Therefore, these keywords cannot be used as an identifier
in VB.NET programming such as class name, variable, function, module, etc.

AddHandler AddressOf Alias And AndAlso As Boolean

ByRef Byte ByVal Call Case Catch CBool

CByte CChar CDate CDec CDbl Char CInt

Class CLng CObj Const Continue CSByte CShort

CSng CStr CType CUInt CULng CUShort Date

Decimal Declare Default Delegate Dim DirectCast Do

Double Each Else ElseIf End End If Enum

Erase Error Event Exit False Finally For

Friend Function Get GetType GetXML Global GoTo


Namespace

Handles If Implements Imports In Inherits Integer

Interface Is IsNot Let Lib Like Long

Loop Me Mod Module MustInherit MustOverride MyBase

MyClass Namespace Narrowing New Next Not Nothing


Not Inheritable Not Object Of On Operator Option
Overridable

Optional Or OrElse Overloads Overridable Overrides ParamArray

Partial Private Property Protected Public RaiseEvent ReadOnly

ReDim REM Remove Resume Return SByte Select


Handler

Set Shadows Shared Short Single Static Step

Stop String Structure Sub SyncLock Then Throw

To True Try TryCast TypeOf UInteger While

Widening With WithEvents WriteOnly Xor

VB.NET Comments

A comment is used to explain the various steps that we have taken in our programming.
The compiler ignores these comment statements because the compiler is not executed or
processed in VB.NET. Therefore, it does not take any place in your compilation code.

In VB.NET, we use ( ' ) symbol to comment a statement.

Data Types in VB.Net


A Data Type refers to which type of data or value is assigning to a variable or function
so that a variable can hold a defined data type value. For example, when we declare a
variable, we have to tell the compiler what type of data or value is allocated to different
kinds of variables to hold different amounts of space in computer memory.
Different Data Types and their allocating spaces in VB.NET

Data Type Storage Allocation Value Range

Boolean Depends on implementing True or False


platform

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
(+/-7.9...E+28) with no decimal point; 0
through +/-
7.9228162514264337593543950335
with 28 places to the right of the decimal

Double 8 bytes -1.79769313486231570E+308 through -


4.94065645841246544E-324, for
negative values
4.94065645841246544E-324 through
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)

Object 4 bytes on 32-bit platform Any type can be stored in a variable of


8 bytes on 64-bit platform type Object

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 implementing 0 to approximately 2 billion Unicode


platform characters

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

ULong 8 bytes 0 through 18,446,744,073,709,551,615


(unsigned)

User- Depends on implementing Each member of the structure has a range


Defined platform determined by its data type and
independent of the ranges of the other
members

UShort 2 bytes 0 through 65,535 (unsigned)

Example
Module DataTypes
Sub Main()
Dim b As Byte
Dim n As Integer
Dim si As Single
Dim d As Double
Dim da As Date
Dim c As Char
Dim s As String
Dim bl As Boolean

b=1
n = 1234567
si = 0.12345678901234566
d = 0.12345678901234566
da = Today
c = "U"c
s = "Me"

If ScriptEngine = "VB" Then


bl = True
Else
bl = False
End If
If bl Then
'the oath taking
Console.Write(c & " and," & s & vbCrLf)
Console.WriteLine("declaring on the day of: {0}", da)
Console.WriteLine("We will learn VB.Net seriously")
Console.WriteLine("Lets see what happens to the floating point variables:")
Console.WriteLine("The Single: {0}, The Double: {1}", si, d)
End If
Console.ReadKey()
End Sub
End Module

The Type Conversion Functions in VB.Net


VB.Net provides the following in-line type conversion functions –

Sr.No. Functions & Description

1 CBool(expression)
Converts the expression to Boolean data type.

2 CByte(expression)
Converts the expression to Byte data type.

3 CChar(expression)
Converts the expression to Char data type.

4 CDate(expression)
Converts the expression to Date data type

5 CDbl(expression)
Converts the expression to Double data type.

6 CDec(expression)
Converts the expression to Decimal data type.

7 CInt(expression)
Converts the expression to Integer data type.

8 CLng(expression)
Converts the expression to Long data type.

9 CObj(expression)
Converts the expression to Object type.
10 CSByte(expression)
Converts the expression to SByte data type.

11 CShort(expression)
Converts the expression to Short data type.

12 CSng(expression)
Converts the expression to Single data type.

13 CStr(expression)
Converts the expression to String data type.

14 CUInt(expression)
Converts the expression to UInt data type.

15 CULng(expression)
Converts the expression to ULng data type.

16 CUShort(expression)
Converts the expression to UShort data type.

Option Strict On
Module DB_Conversion
Sub Main()
'defining the Data type conversion
Dim dblData As Double
dblData = 5.78
Dim A, B As Char
Dim bool As Boolean = True
Dim x, Z, B_int As Integer
A = "A"
B = "B"
B_int = AscW(B)

Console.WriteLine(" Ascii value of B is {0}", B_int)

x=1
Z = AscW(A)
Z=Z+x
Console.WriteLine("String to integer {0}", Z)
Console.WriteLine("Boolean value is : {0}", CStr(bool))
Dim num, intData As Integer

num = CInt(dblData)
intData = CType(dblData, Integer)
Console.WriteLine(" Explicit conversion of Data type " & Str(intData))
Console.WriteLine(" Value of Double is: {0}", dblData)
Console.WriteLine("Double to Integer: {0}", num)
Console.ReadKey()
End Sub
End Module

Output:

Ascii value of B is 66
String to integer 66
Boolean value is: True
Explicit conversion of Data type 6
Value of Double is: 5.78
Double to Integer: 6

Variable Declaration in VB.Net

The Dim statement is used for variable declaration and storage allocation for one or
more variables. The Dim statement is used at module, class, structure, procedure or block
level.

Syntax
Dim Variable_Name as DataType

VariableName: It defines the name of the variable that you assign to store values.

DataType: It represents the name of the data type that you assign to a variable.

Each variable in the variable list has the following syntax and parts –

variablename[ ( [ boundslist ] ) ] [ As [ New ] datatype ] [ = initializer ]


Where,
• variablename − is the name of the variable
• boundslist − optional. It provides list of bounds of each dimension of an array
variable.
• New − optional. It creates a new instance of the class when the Dim statement
runs.
• datatype − Required if Option Strict is On. It specifies the data type of the
variable.
• initializer − Optional if New is not specified. Expression that is evaluated and
assigned to the variable when it is created.

Some valid variable declarations −


Dim StudentID As Integer
Dim StudentName As String
Dim Salary As Double
Dim count1, count2 As Integer
Dim status As Boolean
Dim exitButton As New System.Windows.Forms.Button
Dim lastTime, nextTime As Date

Variable Initialization in VB.Net


Variables are initialized (assigned a value) with an equal sign followed by a constant
expression. The general form of initialization is –

variable_name = value;

Example
Dim pi As Double
pi = 3.14159

You can initialize a variable at the time of declaration as follows −


Dim StudentID As Integer = 100
Dim StudentName As String = "Bill Smith"

Example
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

When the above code is compiled and executed, it produces the following result −
a = 10, b = 20, c = 30
Accepting Values from User
The Console class in the System namespace provides a function ReadLine() for
accepting input from the user and store it into a variable.

Dim message As String


message = Console.ReadLine()

Module variablesNdataypes
Sub Main()
Dim message As String
Console.Write("Enter message: ")
message = Console.ReadLine()
Console.WriteLine()
Console.WriteLine("Your Message: {0}", message)
Console.ReadLine()
End Sub
End Module

Enter message: Hello World


Your Message: Hello World

Lvalues and Rvalues


There are two kinds of expressions –

• lvalue − An expression that is an lvalue may appear as either the left-hand or right-
hand side of an assignment.
• rvalue − An expression that is an rvalue may appear on the right- but not left-hand
side of an assignment.

Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric
literals are rvalues and so may not be assigned and cannot appear on the left-hand side.
Valid statement is −

Dim g As Integer = 20

But following is not a valid statement and would generate compile-time error –

20 = g
VB.NET Operators

In VB.NET programming, the Operator is a symbol that is used to perform various


operations on variables. VB.NET has different types of Operators that help in performing
logical and mathematical operations on data values. The Operator precedence is used
to determine the execution order of different Operators in the VB.NET programming
language.

What is VB.NET Operator?

In VB.NET, operator is a special symbol that tells the compiler to perform the specific
logical or mathematical operation on the data values. The data value itself (which can be
either a variable or a constant) is called an operand, and the Operator performs
various operations on the operand.

For example: In the expression,

3+2-1

The symbol + and - are the Operators, and the 3, 2, and 1 are operands.

Different Types of VB.NET Operators

Following are the different types of Operators available in VB.NET:

o Arithmetic Operators
o Comparison Operators
o Logical and Bitwise Operators
o Bit Shift Operators
o Assignment Operators
o Concatenation Operators
o Miscellaneous Operators

Arithmetic Operators

The Arithmetic Operators in VB.NET, used to perform mathematical operations such


as subtraction, addition, multiplication, division, etc. on the operands in VB.NET.
These are as follows:

Arithmetic Operators in VB.NET

Operators Description Example


^ It is an exponentiation Operator that is used to raises Y ^ X (X to
one operand to the power of another operand. the power Y)

+ The addition Operator is used to add numeric data, as X+Y


well as concatenate two string variables.

- It is a subtraction Operator, which is used to subtract X-Y


the second operand from the first operand.

* The multiplication Operator is used to multiply the X*Y


operands

/ It is a division Operator used to divide one operand X/Y


by another operand and returns a floating-point
result.

\ It is an integer division Operator, which is similar to X\Y


division Operator, except that it returns an integer
result while dividing one operand to another operand.

Mod It is a modulo (Modulus) Operator, which is used to X Mod Y


divide two operands and returns only a remainder.

Example of Arithmetic Operators in VB.NET:

Arithmetic_Operator.vb

Imports System
Module Arithmetic_Operator
Sub Main()
'Declare a, b And c as integer Data Type()
Dim a, b, c As Integer
Dim d As Single
a = 17
b=4
' Use of + Operator
c=a+b
Console.WriteLine(" Sum of a + b is {0}", c)

'Use of - Operator
c=a-b
Console.WriteLine(" Subtraction of a - b is {0}", c)
'Use of * Operator
c=a*b
Console.WriteLine(" Multiplication of a * b is {0}", c)

'Use of / Operator
d=a/b
Console.WriteLine(" Division of a / b is {0}", d)

'Use of \ Operator
c=a\b
Console.WriteLine(" Similar to division Operator (return only integer value) of a - b i
s {0}", c)

'Use of Mod Operator


c = a Mod b
Console.WriteLine(" Modulus of a Mod b is {0}", c)

'Use of ^ Operator
c=a^b
Console.WriteLine(" Power of a ^ b is {0}", c)
Console.WriteLine("Press any key to exit...")
Console.ReadKey()
End Sub
End Module

Now compile and execute the above program, by pressing the F5 button or Start button
from the Visual Studio; then it shows the following result:

Comparison Operators

As the name suggests, the Comparison Operator is used to compare the value of two
variables or operands for the various condition such as greater, less than or equal, etc. and
returns a Boolean value either true or false based on the condition.
Operator Description Example

= It checks whether the value of the two operands is equal; (A = B)


If yes, it returns a true value, otherwise it shows False.

<> It is a Non-Equality Operator that checks whether the (A <> B), check
value of the two operands is not equal; it returns true; Non-Equality
otherwise, it shows false.

> A greater than symbol or Operator is used to determine (A > B); if yes,
whether the value of the left operand is greater than the TRUE,
value of the right operand; If the condition is true, it
returns TRUE; otherwise, it shows FALSE value. Else FALSE

< It is a less than symbol which checks whether the value of (A < B); if the
the left operand is less than the value of the right operand; condition is
If the condition is true, it returns TRUE; otherwise, it true, returns
shows FALSE value. TRUE else
FALSE

>= It is greater than equal to which checks two conditions A >= B


whether the first operand is greater than or equal to the
second operand; if yes, it returns TRUE; otherwise, it
shows False.

<= This symbol represents less than equal to which A <= B


determines the first operand is less than or equal to the
second operand, and if the condition is true, it returns
TRUE; otherwise, it shows FALSE.

Is The Is Operator is used to validate whether the two objects result = obj1 Is
reference the same variable or object; If the test is true, it obj2
returns True; otherwise, the result is False. In short, it
checks the equality of the objects. An Is Operator is also
used to determine whether the object refers to a valid
object.

IsNot The IsNot Operator is similar to Is Operator, except that Result = obj1
the two object references the different object; if yes, the IsNot obj2
result is True; otherwise, the result is False.
Like The Like Operator is used to check the pattern expression result = string
of string variable; And if the pattern matched, the result is Like the
True; otherwise, it returns False. pattern, the
pattern
represents the
series of
characters used
by Like
Operator.

Example of Comparison Operators in VB.NET

Comparison_Operator.vb

Imports System
Module Comparison_Operator
Sub Main()
'declaration of Integer, Object and String Data Type variables
Dim x As Integer = 5
Dim y As Integer = 10
Dim Result, obj, obj2 As Object
Dim str, str2 As String
str = "Apple12345"
str2 = "Apple12345"
obj = 10
obj2 = 20

Console.WriteLine(" Program of Comparison Operator")


'Use of > Operator
Console.WriteLine(" Output of x > y is {0}", x > y)

'Use of < Operator


Console.WriteLine(" Output of x < y is {0}", x < y)

'Use of = Operator
Console.WriteLine(" Output of x = y is {0}", x = y)

'Use of <> Operator


Console.WriteLine(" Output of x <> y is {0}", x <> y)

'Use of >= Operator


Console.WriteLine(" Output of x >= y is {0}", x >= y)
'Use of <= Operator
Console.WriteLine(" Output of x <= y is {0}", x <= y)

'Use of Is Operator
Result = obj Is obj2
Console.WriteLine(" Output of obj Is obj2 is {0}", Result)

'Use of Is Operator
Result = obj IsNot obj2
Console.WriteLine(" Output of obj IsNot obj2 is {0}", Result)

'Use of Like Operator


Result = str Like str2
Console.WriteLine(" Output of str Like str2 is {0}", Result)

Console.WriteLine(" Press any key to exit...")


Console.ReadKey()
End Sub
End Module

Now compile and execute the above code by pressing the F5 button or Start button in
Visual studio, it returns the following output:

Logical and Bitwise Operators

The logical and bitwise Operators work with Boolean (true or false) conditions, and if the
conditions become true, it returns a Boolean value. The following are the logical and
bitwise Operators used to perform the various logical operations such as And, Or, Not,
etc. on the operands (variables). Suppose there are two operand A and B, where A is True,
and B is False.
Operator Description Example

And The And Operator represents, whether both the (A And B),
operands are true; the result is True. result =
False

Or It is an Or Operator that returns a true value; if anyone (A Or B),


operand is true from both the operands. result =
True

Not The Not Operator is used to reverse the logical Not A


condition. For example, if the operand's logic is True,
it reveres the condition and makes it False. Or

Not(A And
B) is True

Xor It is an Exclusive OR Operator that represents, whether A Xor B is


both the expression is true or false, the result is True; True
otherwise, the result is False.

AndAlso It is a logical AND Operator that performs short-circuit A


operation on the variables, and if both the operands are AndAlso B
true, the result is True else the result is False. = False

OrElse It is a logical OR Operator that perform short-circuit A OrElse


operation on Boolean data. If anyone of the operand is B = True
true, the result is True else the result is False.

IsFalse The IsFalse Operator is used to determine whether an


expression is False.

IsTrue The IsTrue Operator is used to determine whether an


expression is True.

Example of Logical and Bitwise Operator:

Logic_Bitwise.vb

Imports System
Module Logic_Bitwise
Sub Main()
Dim A As Boolean = True
Dim B As Boolean = False
Dim c, d As Integer
c = 10
d = 20

'Use of And Operator


If A And B Then
Console.WriteLine(" Operands A And B are True")
End If

'Use of Or Operator
If A Or B Then
Console.WriteLine(" Operands A Or B are True")
End If

'Use of Xor Operator


If A Xor B Then
Console.WriteLine(" Operands A Xor B is True")
End If

'Use of And Operator


If c And d Then
Console.WriteLine(" Operands c And d is True")
End If

'Use of Or Operator
If c Or d Then
Console.WriteLine(" Operands c Or d is True")
End If

'Use of AndAlso Operator


If A AndAlso B Then
Console.WriteLine(" Operand A AndAlso B is True")
End If

'Use of OrElse Operator


If A OrElse B Then
Console.WriteLine(" Operand A OrElse B is True")
End If

'Use of Not Operator


If Not (A And B) Then
Console.WriteLine(" Output of Not (A And B) is True")
End If

Console.WriteLine(" Press any key to exit?")


Console.ReadKey()
End Sub
End Module

Now compile and execute the above code by pressing the F5 button or Start button in
Visual studio, it returns the following output:

Bit Shift Operators

The Bit Shit Operators are used to perform the bit shift operations on binary values either
to the right or to the left.

Bit Shift operations in VB.NET

Operator Description

AND The Binary AND Operator are used to copy the common binary bit in the
result if the bit exists in both operands.

OR The Binary OR Operator is used to copy a common binary bit in the result
if the bit found in either operand.

XOR The Binary XOR Operator in VB.NET, used to determine whether a bit is
available to copy in one operand instead of both.

Not The binary NOT Operator is also known as the binary Ones' Compliment
Operator, which is used to flip binary bits. This means it converts the bits
from 0 to 1 or 1 to 0 binary bits.

<< The Binary Left Shift Operator is used to shift the bit to the left side.
>> The Binary Right Shift Operator is used to shift the bit to the right side.

Example of Bit Shift Operator in VB.NET:

BitShift_Operator.vb

Imports System
Module Bitshift_Operator
Sub Main()
Dim x, y, z As Integer
x = 12
y = 25
Dim a, b As Double
a = 5 ' a = 5(00000101)
b = 9 ' b = 9(00001001)

' Use of And Operator


z = x And y
Console.WriteLine(" BitShift Operator x And y is {0}", z)

'Use of Or Operator
z = x Or y
Console.WriteLine(" BitShift Operator x Or y is {0}", z)

z = x Xor y
Console.WriteLine(" BitShift Operator x Xor y is {0}", z)

z = Not y
Console.WriteLine(" BitShift Operator Not y is {0}", z)

'Use of << Left-Shift Operator


' Output is 00001010
Console.WriteLine(" Bitwise Left Shift Operator - a<<1 = {0}", a << 1)

'Output is 00010010
Console.WriteLine(" Bitwise Left Shift Operator - b<<1 = {0}", b << 1)

'Use of >> Right-Shift Operator


'Output is 00000010
Console.WriteLine(" Bitwise Right Shift Operator - a>>1 = {0}", a << 1)

'Output is 00000100
Console.WriteLine(" Bitwise Right Shift Operator - b>>1 = {0}", a << 1)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module

Now compile and execute the above code by pressing the F5 button or Start button in
Visual studio, it returns the following output:

Assignment Operators

The Assignment Operators are used to assign the value to variables in VB.NET.

Assignment Operators in VB.NET

Operator Description Example

= It is a simple assignment Operator used to X = 5, X assign a


assign a right-side operand or value to a left value 5
side operand. X = P + Q, (P + Q)
variables or value
assign to X.

+= An Add AND assignment Operator is used to X += 5, which means


add the value of the right operand to the left X= X+5 ( 5 will add
operand. And the result is assigned to the left and assign to X and
operand. then result saved to
Left X operand)

-= It is a Subtract AND assignment Operator, X -= P, which is


which subtracts the right operand or value from same as X = X - P
the left operand. And then, the result will be
assigned to the left operand.

*= It is a Multiply AND assignment Operator, X *= P, which is


which multiplies the right operand or value same as X = X - P
with the left operand. And then, the result will
be assigned to the left operand.

/= It is a Divide AND assignment Operator, which X /= P, which is


divides the left operand or value with the right same as X = X - P
operand. And then, the result will be assigned
to the left operand (in floating-point).

\= It is a Divide AND assignment Operator, which X \= P, which is


divides the left operand or value with the right same as X = X - P
operand. And then, the result will be assigned
to the left operand (in integer-point division).

^= It is an expression AND assignment Operator, X ^= P, which is


which raises the left operand or value to the same as X = X ^ P
right operand's power. And then, the result will
be assigned to the left operand.

&= It is a concatenate string assignment Operator Str &= name, which


used to bind the right-hand string or variable is same as Str = Str &
with the left-hand string or variable. And then, name
the result will be assigned to the left operand.
Example of Assignment Operator in VB.NET:

Assign_Operator.vb

Imports System
Module Assign_Operator
Sub Main()
'Declare variable and b As Integer
Dim A As Integer = 5
Dim B As Integer
Dim Str, name As String
name = "come"
Str = "Wel"

'Use of = Operator
B=A
Console.WriteLine(" Assign value A to B is {0}", B)

'Use of += Operator
B += A
Console.WriteLine(" Output of B += A is {0}", B)

'Use of -= Operator
B -= A
Console.WriteLine(" Output of B -= A is {0}", B)

'Use of *= Operator
B *= A
Console.WriteLine(" Output of B *= A is {0}", B)

'Use of /= Operator
B /= A
Console.WriteLine(" Output of B /= A is {0}", B)

'Use of = Operator
B \= A
Console.WriteLine(" Output of B \= A is {0}", B)

'Use of ^= Operator
B ^= A
Console.WriteLine(" Output of B ^= A is {0}", B)

'Use of &= Operator


Str &= name
Console.WriteLine(" Output of Str &= name is {0}", Str)

Console.WriteLine(" Press any key to exit...")


Console.ReadKey()
End Sub
End Module

Now compile and execute the above code by pressing the F5 button or Start button in
Visual studio, it returns the following output:

Concatenation Operators

In VB.NET, there are two concatenation Operators to bind the operands:

Operator Description Example

& It is an ampersand symbol that is used to bind two or Result =


more operand together. Furthermore, a nonstring Wel &
operand can also be concatenated with a string variable come,
( but in that case, Option Strict is on). Result =
Welcome

+ It is also used to add or concatenate two number or Result =


string. Wel +
come,
Result =
Welcome

Example of Concatenation Operators in VB.NET.


MyProgram.vb

Imports System
Module MyProgram
Sub Main()
Dim str As String = "Wel"
Dim str2 As String = "come"
Dim str3 As String = " "
Dim str4 As String = "to JavatPoint"
Dim result As String
Dim result2 As String
result = str & str2
Console.WriteLine(" Result = str & str2 gives = {0}", result)
result2 = str + str2 + str3 + str4
Console.WriteLine(" Result = str + str2 + str3 +str4 gives = {0}", result2.ToString)
Console.ReadLine()
End Sub
End Module

Now compile and execute the above code by pressing the F5 button or Start button in
Visual studio, it returns the following output:
Miscellaneous Operators

There are some important Operator in VB.NET

Operator Description Example

Await An Await Operator is used Dim output as out = Await


in an operand to suspend AsyncMethodThatReturnsResult()
the execution of an Await AsyncMethod()
asynchronous method or
lambda expression until the
awaited task completes.

AddressOf The AddressOf Operator is AddHandler Button2.Click,


used to provide a reference AddressOf Button2_Click
to the address of a
procedure.

GetType A GetType Operator is MsgBox(GetType(String).ToString())


used to retrieve the type of
the specified object. In
addition, the retrieved
object type provides
various information such as
methods, properties, and
events.

Function It defines the lambda Dim mul2 = Function(num As


Expression expression, which declares Integer) num * 4
the parameter and code. A Console.WriteLine(mul2(4))
Lambda expression is a
function that is used to
calculate and return value
without defining the name.

If The If Operator using short Dim a = -4


circuit evaluation to Console.WriteLine(If (a >= 0,
conditionally return a "Positive", "Negative"))
single object value from
two defined object values.
The If Operator can be used
with two or three defined
arguments.

Example of Miscellaneous Operators in VB.NET.

Misc_Operator.vb

Imports System
Module Misc_Operator
Sub Main()
' Initialize a variable
Dim a As Integer = 50
' GetType of the Defined Type
Console.WriteLine(GetType(Double).ToString())
Console.WriteLine(GetType(Integer).ToString())
Console.WriteLine(GetType(String).ToString())
Console.WriteLine(GetType(Single).ToString())
Console.WriteLine(GetType(Decimal).ToString())

'Use of Function()
Dim multiplywith10 = Function(sum As Integer) sum * 10
Console.WriteLine(multiplywith10(10))
Console.WriteLine(If(a >= 0, "Negative", "Positive"))

Console.WriteLine(" Press any key to exit...")


Console.ReadLine()

End Sub
End Module

Now compile and execute the above code by pressing the F5 button or Start button in
Visual studio, it returns the following output:

Operator Precedence in VB.NET


Operator precedence is used to determine the order in which different Operators in a
complex expression are evaluated. There are distinct levels of precedence, and an
Operator may belong to one of the levels. The Operators at a higher level of precedence
are evaluated first. Operators of similar precedents are evaluated at either the left-to-right
or the right-to-left level.

The Following table shows the operations, Operators and their precedence -

Operations Operators Precedence

Await Highest

Exponential ^

Unary identity and negation +, -

Multiplication and floating-point *, /


division

Integer division \

Modulus arithmetic Mod

Addition and Subtraction +, -

Arithmetic bit shift <<, >>

All comparison Operators =, <>, <, <=, >, >=, Is,


IsNot, Like, TypeOf
…is

Negation Not

Conjunction And, AndAlso

Inclusive disjunction Or, Else

Exclusive disjunction Xor Lowest

Example of Operator Precedence in VB.NET.

Operator_Precedence.vb

Imports System
Module Operator_Precedence
Sub Main()
'Declare and Initialize p, q, r, s variables
Dim p As Integer = 30
Dim q As Integer = 15
Dim r As Integer = 10
Dim s As Integer = 5
Dim result As Integer

Console.WriteLine("Check Operator Precedence in VB.NET")


'Check Operator Precedence
result = (p + q) * r / s ' 45 * 10 / 5
Console.WriteLine("Output of (p + q) * r / s is : {0}", result)

result = (p + q) * (r / s) ' (45) * (10/5)


Console.WriteLine("Output of (p + q) * (r / s) is : {0}", result)

result = ((p + q) * r) / s ' (45 * 10 ) / 5


Console.WriteLine("Output of ((p + q) * r) / s is : {0}", result)

result = p + (q * r) / s ' 30 + (150/5)


Console.WriteLine("Output of p + (q * r) / s is : {0}", result)

result = ((p + q * r) / s) ' ((30 + 150) /5)


Console.WriteLine("Output of ((p + q * r) / s) is : {0}", result)

Console.WriteLine(" Press any key to exit...")


Console.ReadKey()
End Sub
End Module

Now compile and execute the above code by pressing the F5 button or Start button in
Visual studio, it returns the following output:
VB.NET Control Statements

In VB.NET, the control statements are the statements that controls the execution of the
program on the basis of the specified condition. It is useful for determining whether a
condition is true or not. If the condition is true, a single or block of statement is executed.
In the control statement, we will use if- Then, if Then Else, if Then ElseIf and the Select
case statement.

We can define more than one condition to be evaluated by the program with statements.
If the defined condition is true, the statement or block executes according to the condition,
and if the condition is false, another statement is executed.

The following figure shows a common format of the decision control statements to
validate and execute a statement:
The above diagram shows that if the defined condition is true, statement_1 will be
executed, and if the condition is false, statement_2 will be executed.

VB.NET provides the following conditional or decision-making statements.

o If-Then Statement
o If-Then Else Statement
o If-Then ElseIf Statement
o Select Case Statement
o Nested Select Case Statements

If-Then Statement

The If-Then Statement is a control statement that defines one or more conditions, and if
the particular condition is satisfied, it executes a piece of information or statements.

Syntax:

1. If condition Then
2. [Statement or block of Statement]
3. End If

In If-Then Statement, the condition can be a Boolean, logical, or relational condition,


and the statement can be single or group of statements that will be executed when the
condition is true.

Example 1: Write a simple program to print a statement in VB.NET.

Module1.vb

1. Module Module1
2. ' Declaration of variable str
3. Dim str As String = "JavaTpoint"
4. Sub Main()
5. ' if str equal to "JavaTpoint", below Statement will be executed.
6. If str = "JavaTpoint" Then
7. Console.WriteLine("Welcome to the JavaTpoint")
8. End If
9. Console.WritLine("press any key to exit?")
10. Console.ReadKey()
11. End Sub
12.End Module
Now compile and execute the above program by clicking on the Start or F5 button, it
shows the following output:

As we can see in the above example, if the value of str is equal to JavaTpoint, the
condition is true, and it prints the Statement.

Example 2: Write a program to print a number is greater than another number in


VB.NET.

if_statment2.vb

1. Module if_statement2
2. Sub Main()
3. ?Definition of variables
4. Dim no1, no2 As Integer
5. Console.WriteLine("Enter any two number:")
6. no1 = Console.ReadLine() ?read no1 from user
7. no2 = Console.ReadLine() ?read no2 from user
8. If no1 > no2 Then
9. Console.WriteLine("First number is greater than second number")
10. End If
11. If no1 < no2 Then
12. Console.WriteLine("Second number is greater than First number")
13. End If
14. Console.WriteLine("press any key to exit...")
15. Console.ReadKey()
16.End Sub
17.End Module

Now compile and execute the above program by clicking on the Start or F5 button, it
shows the following output:
In the above program, we enter two numbers to find the greater number using the
relational operator. And if the first number is greater than the other, the first statement is
executed; otherwise, the second statement will be executed.

If-Then-Else Statement

The If-Then Statement can execute single or multiple statements when the condition is
true, but when the expression evaluates to false, it does nothing. So, here comes the If-
Then-Else Statement. The IF-Then-Else Statement is telling what If condition to do
when if the statement is false, it executes the Else statement. Following is the If-Then-
Else statement syntax in VB.NET as follows:

Syntax:

1. If (Boolean_expression) Then
2. 'This statement will execute if the Boolean condition is true
3. Else
4. 'Optional statement will execute if the Boolean condition is false
5. End If

Flow chart
The above diagram represents that if the Boolean expression (condition) is true, the if
statement will execute, and if the Boolean expression is false, Else code or
statement will be executed. After that, the control transfer to the next statement, which
is immediately after the If-Then-Else control statement.

Example 1: Write a program to check whether the number is even or odd.

If_Else_statment.vb

1. Module If_Else_statement
2. Sub Main()
3. Dim num As Integer
4. Console.WriteLine("Enter the Number")
5. num = Console.ReadLine() 'read data from console
6.
7. If (num Mod 2 = 0) Then ' if condition is true, print the if statement
8. Console.WriteLine("It is an even number")
9.
10. Else 'otherwise, Else statement is executed.
11. Console.WriteLine("It is an odd number")
12. End If
13.
14. Console.WriteLine("press any key to exit...")
15. Console.ReadKey()
16. End Sub
17.End Module

Now compile and execute the above program by clicking on the Start or F5 button, it
shows the following output:

Example 2: Write a program to print the larger and smaller of the two numbers.

if_else_statment2.vb

1. Module if_else_statement2
2. Sub Main()
3. Dim a As Integer
4. Dim b As Integer
5. Console.WriteLine("Enter the first number : ")
6. a = Console.ReadLine()
7.
8. Console.WriteLine("Enter the second number : ")
9. b = Console.ReadLine()
10.
11. If a > b Then
12. Console.WriteLine(" larger number = {0} and smaller number = {1} ", a, b)
13. Else
14. Console.WriteLine(" larger number = {0} and smaller number = {1} ", b, a)
15. End If
16.
17. Console.WriteLine("press any key to exit...")
18. Console.ReadKey()
19. End Sub
20.End Module
Now compile and execute the above program by clicking on the Start or F5 button, it
shows the following output:

VB.NET If-Then-ElseIf statement

The If-Then-ElseIf Statement provides a choice to execute only one condition or


statement from multiple statements. Execution starts from the top to bottom, and it
checked for each If condition. And if the condition is met, the block of If the statement is
executed. And if none of the conditions are true, the last block is executed. Following is
the syntax of If-Then-ElseIf Statement in VB.NET as follows:

Syntax

1. If(condition 1)Then
2. ' Executes when condition 1 is true
3. ElseIf( condition 2)Then
4. ' Executes when condition 2 is true
5. ElseIf( boolean_expression 3)Then
6. ' Executes when the condition 3 is true
7. Else
8. ' executes the default statement when none of the above conditions is true.
9. End If

Flowchart

The following diagram represents the functioning of the If-Else-If Statement in the
VB.NET programming language.
If this condition is true in the flowchart of the if-else-if statement, the statement is
executed within the if block. If the condition is not true, it passes control to the next ElseIf
condition to check whether the condition is matched. And if none of the conditions are
matched, the else block is executed.

Example 1: Write a program to show the uses of If... ElseIf statements.

if_elseIf.vb

1. Module if_elseIf
2. Sub Main()
3. Dim var1 As Integer
4.
5. Console.WriteLine(" Input the value of var1: ")
6. var1 = Console.ReadLine()
7. If var1 = 20 Then
8. 'if condition is true then print the following statement'
9. Console.WriteLine(" Entered value is equal to 20")
10. ElseIf var1 < 50 Then
11. Console.WriteLine(" Entered value is less than 50")
12.
13. ElseIf var1 >= 100 Then
14. Console.WriteLine(" Entered value is greater than 100")
15. Else
16. 'if none of the above condition is satisfied, print the following statement
17. Console.WriteLine(" Value is not matched with above condition")
18. End If
19. Console.WriteLine(" You have entered : {0}", var1)
20. Console.WriteLine(" press any key to exit...")
21. Console.ReadKey()
22. End Sub
23.End Module

Now compile and execute the above program by clicking on the Start or F5 button, it
shows the following output:

Example 2: Write a program to use the If-Then-ElseIf Statement for calculating the
division obtained by the student. Also, take the marks obtained by the student in 5
different subjects from the keyboard.

if_elseIf2.vb

1. Module If_elseIf2
2. Sub Main() ' execution start from Main() method
3. Dim m1, m2, m3, m4, m5, per As Integer
4. Console.WriteLine("Enter marks in five subjects ")
5. ' Read the marks of five subject
6. m1 = Console.ReadLine()
7. m2 = Console.ReadLine()
8. m3 = Console.ReadLine()
9. m4 = Console.ReadLine()
10. m5 = Console.ReadLine()
11. per = (m1 + m2 + m3 + m4 + m5) / 5
12. If (per >= 70) Then
13. 'if condition is true, print the first division
14. Console.WriteLine(" First division")
15. ElseIf (per >= 60) Then
16. 'if ElseIf condition is true, print the second division
17. Console.WriteLine(" Second division")
18. ElseIf (per >= 50) Then
19. 'if ElseIf condition is true, print the third division
20. Console.WriteLine(" Third division")
21. ElseIf (per >= 40) Then
22. 'if ElseIf condition is true, print only pass with grace
23. Console.WriteLine(" Only Pass with Grace")
24. Else
25. 'if none of the condition is true, print the Failed
26. Console.WriteLine(" Failed")
27. End If
28. Console.WriteLine("press any key to exit...")
29. Console.ReadKey()
30. End Sub
31.
32.End Module

Now compile and execute the above program by clicking on the Start or F5 button, it
shows the following output:

Select Case Statement

In VB.NET, the Select Case statement is a collection of multiple case statements, which
allows executing a single case statement from the list of statements. A selected case
statement uses a variable to test for equality against multiple cases or statements in a
program. If the variable is matched with any test cases, that statement will be executed.
And if the condition is not matched with any cases, it executes the default statement.
Using the select case statement in VB.NET programming, you can replace the uses of
multiple If-Then-Else If statement from the program for better readability and easy to
use.

Syntax

Following is the syntax of the Select Case statement in VB.NET, as follows:

1. Select Case [variable or expression]


2. Case value1 'defines the item or value that you want to match.
3. // Define a statement to execute
4.
5. Case value2 'defines the item or value that you want to match.
6. // Define a statement to execute
7.
8. Case Else
9. // Define the default statement if none of the conditions is true.
10.End Select

Furthermore, you can also set more than one condition in a single case statement, such
as:

1. Select Case Variable / expression


2. Case value1
3. Statement1
4.
5. Case value2, value3
6. Statement2
7.
8. Case Else
9. // define the default statement if none of the condition is true
10.End Select

Flowchart of Select Case Statement

The following flowchart represents the functioning of the Select case statement in the
VB.NET programming language.
In Flowchart, the Select Case statement represents the evaluating of the process start from
top to bottom. If the expression or value is matched with the first select case, statement -
1 is executed else the control transfer to the next case for checking whether the expression
is matching or not. Similarly, it checks all Select case statements for evaluating. If none
of the cases are matched, the Else block statement will be executed, and finally, the Select
Case Statement will come to an end.

Example 1: Write a program to display the Days name using the select case statement in
VB.NET.

Select_case.vb

Imports System
Module Select_case
Sub Main()
'define a local variable.
Dim Days As String
Days = "Thurs"
Select Case Days
Case "Mon"
Console.WriteLine(" Today is Monday")
Case "Tue"
Console.WriteLine(" Today is Tuesday")
Case "Wed"
Console.WriteLine("Today is Wednesday")
Case "Thurs"
Console.WriteLine("Today is Thursday")
Case "Fri"
Console.WriteLine("Today is Friday")
Case "Sat"
Console.WriteLine("Today is Saturday")
Case "Sun"
Console.WriteLine("Today is Sunday")
Case Else
Console.WriteLine(" You have typed Something wrong")

End Select
Console.WriteLine("You have selected : {0}", Days)
Console.WriteLine("Press any key to exit...")
Console.ReadLine()
End Sub
End Module

Now compile and execute the above program by clicking on the Start or F5 button, it
shows the following output:

In the select case statement, the value of Days "Thurs" will compare all the
available select cases' values in a program. If a value matched with any condition, it prints
the particular statement, and if the value is not matched with any select case statement, it
prints the default message.

Example 2: Write a program to perform an arithmetic operation using the Select case
statement in VB.NET.
Operation.vb

Operation.vb

Imports System
Module Operation
Sub main()
'declaration of the variables
Dim num1, num2, sum As Integer
Dim def As Char
'initialization of num1 and num2 variable
num1 = 2
num2 = 6
Console.WriteLine(" Want to perform any operation?")
Console.WriteLine(" A for Addition")
Console.WriteLine(" S for Subtraction")
Console.WriteLine(" M for Multiplication")
Console.WriteLine(" D for Division")
Console.WriteLine(" Please enter any input")
def = Console.ReadLine()
Select Case def
Case "A"
'perform Addition
sum = num1 + num2
Console.WriteLine(" Addition of two number is :{0}", sum)
Case "S"
'perform Subtraction
sum = num2 - num1
Console.WriteLine(" Subtraction of two number is :{0}", sum)
Case "M"
'perform Multiplication
sum = num1 * num2
Console.WriteLine(" Multiplication of two number is :{0}", sum)
Case "D"
'Peform Division
sum = num2 / num1
Console.WriteLine(" Division of two number is :{0}", sum)
Case Else
'If none of the operation matched, call default statement
Console.WriteLine(" Please enter only define operation With Capital letter")
End Select
Console.WriteLine("Press any key to exit...")
Console.ReadKey()
End Sub
End Module

Now compile and execute the above program by clicking on the Start or F5 button, it
shows the following output:

In the above example, we defined Select with multiple case statements, and if the user-
defined input is matched with any defined case statement, it executes that statement. And
if the condition is not matched with any case, it executes a default statement in VB.NET.

Here, we provide 'M' as input, which checks all case statements, and if any case is
matched with M, it executes the statement within the respective Case statement.

VB.NET Nested Select Case statements

When a Select Case statement is written inside the body of another Select Case
statement is called a nested Select Case statement.

Syntax:

Select Case "num"


' code to be executed if num = 1
Case 1
' nested Select case
Select Case n

' code to be executed if n = 5


Case 5
Statement 1

' code to be executed if n = 10


Case 10
Statement 2

' code to be executed if n = 15


Case 15
Statement 3

' code to be executed if n doesn't match with any cases.


Case Else
Statement

' code to be executed if num = 2


Case 2
Statement 2

' code to be executed if num = 3


Case 3
Statement 3

' code to be executed if num doesn't match with any cases.


Case Else
Statement

Example 1: Write a program to use a nested select case statement in VB.NET.

Module1.vb

Module Module1

Sub Main()

Dim x As Integer = 10, y As Integer = 5


Select Case x

Case 10
Console.WriteLine("X Value: 10")

Select Case y
Case 5
Console.WriteLine("Nested Switch Value: 5")

Select Case y - 2
Case 3
Console.WriteLine("Another Nested Switch Value: 3")

End Select
End Select

Case 15
Console.WriteLine("X Value: 15")

Case 20
Console.WriteLine("X Value: 20")

Case Else
Console.WriteLine("Not Known")

End Select
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module

Now compile and execute the above program by clicking on the Start or F5 button, it
shows the following output:

Example 2: Write a program to use the nested select case statement in VB.NET.

nested_selectcase.vb

Imports System
Module nested_selectcase
Sub Main()
Dim num As Integer
Dim str As String
str = "F"
Console.WriteLine(" Enter only First three number like 1, 2, 3")
num = Console.ReadLine() 'take input from the user
Select Case num
Case 1
Console.WriteLine(" You are in block 1")
Console.WriteLine("Only First two letter such as A and B")

str = Console.ReadLine()
Select Case str
Case "A", "a"
Console.WriteLine(" This is a VB.NET Tutorial")
Case "B", "b"
Console.WriteLine(" Welcome to the JavaTpoint")
Case Else
Console.WriteLine(" Something is wrong")
End Select

Case 2
Console.WriteLine(" You are in block 2")
Console.WriteLine("Only First two letter such as C and D")
str = Console.ReadLine()
Select Case str
Case "C", "c"
Console.WriteLine(" Welcome to the World!")
Case "D", "d"
Console.WriteLine(" Want to go in Heaven")
Case Else
Console.WriteLine(" Something is wrong")
End Select

Case 3
Console.WriteLine(" You are in block 3")
Console.WriteLine("Only First two letter such as E and F")
str = Console.ReadLine()
Select Case str
Case "E", "e"
Console.WriteLine(" VB.NET is a programming language to develop we
b, window, and console-based application. ")
Case "F", "f"
Console.WriteLine(" You have to basic knowledge of c and c++")
Case Else
Console.WriteLine(" Something is wrong")
End Select
Case Else
Console.WriteLine(" Something is wrong")
End Select
Console.ReadLine()
End Sub
End Module

Now compile and execute the above program by clicking on the Start or F5 button, it
shows the following output:

In the above example, we have only defined the first three numbers 1-3 and if the number
matches to any case statement, the select statement is executed. Here, we have entered 2
that is matched with case 2 and it executes a block as shown above. And this block
executes the statement "Only the First two letters such as C and D". Therefore, we enter
a letter D, letter D is matched with the nested select case statement, and if a match is
found, it executes the select case statement as shown above.
Looping Statements

Those statements, which are used to execute a set of statements again & again until the
given condition remains TRUE, are known as LOOPING STATEMENTS.

In another word, we can also say that these statements are used to repeat a certain task
until a certain period. That‘s why; it is also called REPETATIVE STATEMENTS or ITERATIVE
STATEMENT.

There are several types of looping statements supported by VB:

1. FOR – LOOP
2. WHILE – LOOP
3. DO – WHILE – LOOP
4. DO – UNTIL LOOP
5. DO – LOOP – WHILE
6. DO – LOOP- UNTIL
7. FOR EACH

1. FOR LOOP: -

It is looping statement which can repeat the set statements written within its body until
the given condition remains true.

Syntax: -

For variable = initial_value To final_value STEP <step_value>


Statement
-------------
-------------

Next variable

The Initial value indicates that from which value the loop will be started.

The Final value indicates that until which value, the loop will be repeated.
The STEP is the keyword and step value indicates that by which values the

looping variable is increased or decreased after each repetition. If it is not mentioned


than the FOR – LOOP variable is increased by 1 by default.

2. WHILE LOOP:-

It is also looping statement, which can repeat the statements until some

condition is satisfied.
Syntax: -

While (condition)

Statement
----------------

----------------
Increment/ Decrement part

Wend

The initial value of WHILE LOOP variable must be assigned above the WHILE LOOP. The
condition is mentioned with the loop, which specifies that how much times the loop will
be repeated.

3. DO – WHILE- LOOP:-

It is also looping statement, which is same as the WHILE – LOOP. But the difference
between WHILE - LOOP and DO – WHILE LOOP is that WHILE – LOOP cannot be
terminated before reaching on given condition but the DO – WHILE LOOP can be
terminated on some condition before reaching on given condition.

The DO – WHILE, DO – UNTIL, DO – LOOP –WHILE and DO – LOOP – UNTIL is the looping
statements of DO – LOOP series.

Syntax: -

Do while (condition)

Statement
----------------
----------------
Increment/Decrement part

Loop

4. DO – UNTIL- LOOP:-

It is also a looping statement of DO – LOOP series. It checks the condition for


falsity. It means, it checks the condition in negative and executes the body unless and
until the given condition evaluates to false.

When the condition is being TRUE, then the loop is terminated.

Syntax: -

Do until (condition)

Statement
----------------

----------------
Increment/Decrement

Loop

5. DO - LOOP - WHILE:-

It is also a looping statement which must executes the statements at least once. Like
WHILE – LOOP and DO – WHILE – LOOP, it is also check the condition for true & repeats
the body unless and until, the given condition remains TRUE.
Syntax: -

Do

Statement
----------------

----------------
Increment/Decrement

Loop While (condition)

6. DO - LOOP - UNTIL:-

It is also a looping statement which must executes the statements at least once. But, it
checks the condition for falsity. That is, it repeats the statement unless and until the
given condition remains false.

Syntax: -

Do

Statement
----------------

----------------
------------

Increment/Decrement

Loop until (condition)


Exit Loop and Exit For Statement:

Exit Do and ―Exit For statement is used to terminate the loop on some condition before
satisfying the given condition.

The Exit Loop statement is used to terminate the DO – LOOP, DO WHILE – LOOP .

And the Exit For statement is used to terminate the FOR – LOOP on some condition.

Syntax: -

Do while (condition)

------------------

------------------

If (condition)

Exit loop

End if
Loop

For variable = initial_value To final_value STEP <step_value>

-------------

-------------
If (condition)
Exit for

End if

Next variable

8. FOR EACH

For Each var in List


Statement
Next var
ARRAY

Array is a derived or user defined data type, which is used to store more than one values
of same data type. It means, it is used to store homogenous types of data.

Hence, in the case, variable name is same for more than one values of same data
type.

An array stores a fixed-size sequential collection of elements of the same type. An array
is used to store a collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.
All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.

Syntax: -
Dim a (10) as integer
Dim b (10) as single
Dim c (10) as string
Creating Arrays in VB.Net
To declare an array in VB.Net, you use the Dim statement. For example,
Dim intData(30) ' an array of 31 elements
Dim strData(20) As String ' an array of 21 strings
Dim twoDarray(10, 20) As Integer 'a two dimensional array of integers
Dim ranges(10, 100) 'a two dimensional array
You can also initialize the array elements while declaring the array. For example,
Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
Dim names() As String = {"Karthik", "Sandhya", _
"Shivangi", "Ashwitha", "Somnath"}
Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}
There are two types of arrays: -
1. Single Dimensional Array

2. Multi Dimensional Array

1. SINGLE DIMENSIONAL ARRAY: -

When one dimension is mentioned with an array variable than it is known as Single
Dimensional Array.

Syntax: -
Dim variable (size) As Data type

Example: -

Dim a (10) As Integer

The memory is allocated by the array variable name either horizontally or vertically and
whole space is divided into different blocks according to the given size. Each block is
given the unique numerical number (starts from 0), known as INDEX NUMBER / BLOCK
NUMBER / POCKET NUMBER. Each block has the same size and has capacity to hold one
number at a time.

Example: -

Dim a (5) As Integer

0 1 2 3 4

Now, the value is assigned or retrieved to or from an array variable, by using the
variable name and index number.

_____________________________________
Assignment Retrieve

_____________________________________
a (2) = 10 | print a (2)
a (4) = 40 | print a (4)

The array variable can also be declared as follows: -

Syntax: -

Dim variable (v1 to v2) As Integer

Example: -
Dim a (0 to 10) As Integer

0 1 2 3 4 5 6 7 8 9 10

2. MULTI- DIMENSIONAL ARRAY: -

When more than one dimension is mentioned in an array variable, then it is known as
Multi – Dimensional array.

They include Double Dimensional, Triple Dimensional etc.

Double Dimensional Array: -

When two dimensions is mentioned with an array variable, and then it is known as
Double Dimensional array.

Syntax: -

Dim variable (Size. Size) As Integer

The first ―size stands for row value and the second size stands for column value.
The memory space is allocated by the DDA variable name and whole space is divided
into different row and column according to specified dimensions. Each row and column
is numbered by an index number, starts from Zero (0).
Example: -

Dim a (2, 2) As Integer

The memory space is allocated as follows:

The combination of row and column is known as cell. So, the data is stored in DDA
according to cell wise.

We can also declare the DDA as follows:

Dim a (0 to 2, 0 to 2) As Integer
The elements in an array can be stored and accessed by using the index of the array.
The following program demonstrates this −
Module arrayApl
Sub Main()
Dim n(10) As Integer ' n is an array of 11 integers '
Dim i, j As Integer
' initialize elements of array n '

For i = 0 To 10
n(i) = i + 100 ' set element at location i to i + 100
Next i
' output each array element's value '

For j = 0 To 10
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110
Dynamic Arrays
Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the
need of the program. You can declare a dynamic array using the ReDim statement.
Syntax for ReDim statement −
ReDim [Preserve] arrayname(subscripts)
Where,
• The Preserve keyword helps to preserve the data in an existing array, when you
resize it.
• arrayname is the name of the array to re-dimension.
• subscripts specifies the new dimension.
Module arrayApl
Sub Main()
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
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
9 0
10 0
Multi-Dimensional Arrays
VB.Net allows multidimensional arrays. Multidimensional arrays are also called
rectangular arrays.
You can declare a 2-dimensional array of strings as −
Dim twoDStringArray(10, 20) As String
or, a 3-dimensional array of Integer variables −
Dim threeDIntArray(10, 10, 10) As Integer
The following program demonstrates creating and using a 2-dimensional array −
Module arrayApl
Sub Main()
' an array with 5 rows and 2 columns
Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}
Dim i, j As Integer
' output each array element's value '

For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8
Jagged Array
A Jagged array is an array of arrays. The following code shows declaring a jagged array
named scores of Integers −
Dim scores As Integer()() = New Integer(5)(){}
The following example illustrates using a jagged array −
Module arrayApl
Sub Main()
'a jagged array of 5 array of integers
Dim a As Integer()() = New Integer(4)() {}
a(0) = New Integer() {0, 0}
a(1) = New Integer() {1, 2}
a(2) = New Integer() {2, 4}
a(3) = New Integer() {3, 6}
a(4) = New Integer() {4, 8}
Dim i, j As Integer
' output each array element's value

For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i)(j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
The Array Class
The Array class is the base class for all the arrays in VB.Net. It is defined in the System
namespace. The Array class provides various properties and methods to work with
arrays.
Properties of the Array Class
The following table provides some of the most commonly used properties of
the Array class −
Sr.No Property Name & Description

1 IsFixedSize
Gets a value indicating whether the Array has a fixed size.

2 IsReadOnly
Gets a value indicating whether the Array is read-only.
3 Length
Gets a 32-bit integer that represents the total number of elements in all the
dimensions of the Array.

4 LongLength
Gets a 64-bit integer that represents the total number of elements in all the
dimensions of the Array.

5 Rank
Gets the rank (number of dimensions) of the Array.
Methods of the Array Class
The following table provides some of the most commonly used methods of
the Array class −
Sr.No Method Name & Description

1 Public Shared Sub Clear (array As Array, index As Integer, length As Integer)
Sets a range of elements in the Array to zero, to false, or to null, depending
on the element type.

2 Public Shared Sub Copy (sourceArray As Array, destinationArray As Array,


length As Integer)
Copies a range of elements from an Array starting at the first element and
pastes them into another Array starting at the first element. The length is
specified as a 32-bit integer.

3 Public Sub CopyTo (array As Array, index As Integer)


Copies all the elements of the current one-dimensional Array to the specified
one-dimensional Array starting at the specified destination Array index. The
index is specified as a 32-bit integer.

4 Public Function GetLength (dimension As Integer) As Integer


Gets a 32-bit integer that represents the number of elements in the specified
dimension of the Array.

5 Public Function GetLongLength (dimension As Integer) As Long


Gets a 64-bit integer that represents the number of elements in the specified
dimension of the Array.

6 Public Function GetLowerBound (dimension As Integer) As Integer


Gets the lower bound of the specified dimension in the Array.
7 Public Function GetType As Type
Gets the Type of the current instance (Inherited from Object).

8 Public Function GetUpperBound (dimension As Integer) As Integer


Gets the upper bound of the specified dimension in the Array.

9 Public Function GetValue (index As Integer) As Object


Gets the value at the specified position in the one-dimensional Array. The
index is specified as a 32-bit integer.

10 Public Shared Function IndexOf (array As Array,value As Object) As Integer


Searches for the specified object and returns the index of the first occurrence
within the entire one-dimensional Array.

11 Public Shared Sub Reverse (array As Array)


Reverses the sequence of the elements in the entire one-dimensional Array.

12 Public Sub SetValue (value As Object, index As Integer)


Sets a value to the element at the specified position in the one-dimensional
Array. The index is specified as a 32-bit integer.

13 Public Shared Sub Sort (array As Array)


Sorts the elements in an entire one-dimensional Array using the IComparable
implementation of each element of the Array.

14 Public Overridable Function ToString As String


Returns a string that represents the current object (Inherited from Object).
For complete list of Array class properties and methods, please consult Microsoft
documentation.
Example
The following program demonstrates use of some of the methods of the Array class:
Module arrayApl
Sub Main()
Dim list As Integer() = {34, 72, 13, 44, 25, 30, 10}
Dim temp As Integer() = list
Dim i As Integer
Console.Write("Original Array: ")

For Each i In list


Console.Write("{0} ", i)
Next i
Console.WriteLine()
' reverse the array
Array.Reverse(temp)
Console.Write("Reversed Array: ")

For Each i In temp


Console.Write("{0} ", i)
Next i
Console.WriteLine()
'sort the array
Array.Sort(list)
Console.Write("Sorted Array: ")

For Each i In list


Console.Write("{0} ", i)
Next i
Console.WriteLine()
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Original Array: 34 72 13 44 25 30 10
Reversed Array: 10 30 25 44 13 72 34
Sorted Array: 10 13 25 30 34 44 72

You might also like