Notes
Notes
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.
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.
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.
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.
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:
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.
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.
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
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.
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.
Hello, World!
• 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 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 –
• 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.
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.
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.
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"
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)
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
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 –
variable_name = value;
Example
Dim pi As Double
pi = 3.14159
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.
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
• 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, 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.
3+2-1
The symbol + and - are the Operators, and the 3, 2, and 1 are operands.
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
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 ^ 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 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
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.
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
'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)
Now compile and execute the above code by pressing the F5 button or Start button in
Visual studio, it returns the following output:
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
Not(A And
B) is True
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 Or Operator
If A Or B Then
Console.WriteLine(" Operands A Or B are True")
End If
'Use of Or Operator
If c Or d Then
Console.WriteLine(" Operands c Or d is True")
End If
Now compile and execute the above code by pressing the F5 button or Start button in
Visual studio, it returns the following output:
The Bit Shit Operators are used to perform the bit shift operations on binary values either
to the right or to the left.
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.
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 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)
'Output is 00010010
Console.WriteLine(" Bitwise Left Shift Operator - b<<1 = {0}", b << 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.
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)
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
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
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"))
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:
The Following table shows the operations, Operators and their precedence -
Await Highest
Exponential ^
Integer division \
Negation Not
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
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.
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
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.
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.
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:
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.
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:
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
Furthermore, you can also set more than one condition in a single case statement, such
as:
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.
When a Select Case statement is written inside the body of another Select Case
statement is called a nested Select Case statement.
Syntax:
Module1.vb
Module Module1
Sub Main()
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.
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: -
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
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:-
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
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
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
-------------
-------------
If (condition)
Exit for
End if
Next variable
8. FOR EACH
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
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: -
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: -
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)
Syntax: -
Example: -
Dim a (0 to 10) As Integer
0 1 2 3 4 5 6 7 8 9 10
When more than one dimension is mentioned in an array variable, then it is known as
Multi – Dimensional array.
When two dimensions is mentioned with an array variable, and then it is known as
Double Dimensional array.
Syntax: -
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: -
The combination of row and column is known as cell. So, the data is stored in DDA
according to cell wise.
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
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.