You are on page 1of 21

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.

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

○ If-Then Statement

○ If-Then Else Statement

○ If-Then ElseIf Statement

○ Select Case Statement


○ 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:

If condition Then

[Statement or block of Statement]

End If

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:

If (Boolean_expression) Then

'This statement will execute if the Boolean condition is true

Else

'Optional statement will execute if the Boolean condition is false


End If

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

If(condition 1)Then

' Executes when condition 1 is true

ElseIf( condition 2)Then

' Executes when condition 2 is true

ElseIf( boolean_expression 3)Then

' Executes when the condition 3 is true

Else

' executes the default statement when none of the above conditions is true.

End If

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.

Syntax

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

Select Case [variable or expression]

Case value1 'defines the item or value that you want to match.

// Define a statement to execute

Case value2 'defines the item or value that you want to match.

// Define a statement to execute

Case Else

// Define the default statement if none of the conditions is true.

End Select

Choose Function:Definition: The Choose function returns a value from a list of


arguments based on an index number. It's like an array where you pick a value based on
its position. The first argument is the index, followed by the possible values.
Example:

vb.net

Dim day As Integer = 3

Dim dayName As String

dayName = Choose(day, "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",


"Saturday", "Sunday")

Console.WriteLine(dayName) ' Outputs: Wednesday

In the example above, since day is 3, the third value from the list ("Wednesday") is
chosen.

Switch Function: Definition: The Switch function evaluates a list of expressions and
returns the value of the first expression that is true. Each pair of arguments consists of
a condition and a result. If the condition is True, the result of that pair is returned.

Example:

Vb.net

Dim score As Integer = 85

Dim grade As String

grade = Switch(

score >= 90, "A",

score >= 80, "B",

score >= 70, "C",


score >= 60, "D",

True, "F"

Console.WriteLine(grade) ' Outputs: B

In the example above, the function checks each condition. The condition score >= 80 is
the first true condition, so "B" is returned.

Loops

In VB.NET, loop statements allow you to execute a block of code multiple times based
on a condition or a set number of iterations. Let's delve into each type of loop available
in VB.NET.

1. For...Next Loop:

Definition: Executes a sequence of statements a set number of times.

Example:

vb.net

For i As Integer = 1 To 5

Console.WriteLine(i)

Next

This will print numbers 1 through 5.


2. For Each...Next Loop:

Definition: Iterates over each item in a collection or an array.

Example:

vb.net

Dim fruits As String() = {"Apple", "Banana", "Cherry"}

For Each fruit In fruits

Console.WriteLine(fruit)

Next

This will print each fruit name in the fruits array.

3. While...End While Loop:

Definition: Repeats a block of statements as long as a condition remains true.

Example:

vb.net

Dim num As Integer = 1

While num <= 5


Console.WriteLine(num)

num += 1

End While

This will print numbers 1 through 5.

4. Do...Loop While:

Definition: Executes a block of statements and then continues to do so as long as a


condition remains true.

Example:

vb.net

Dim num As Integer = 1

Do

Console.WriteLine(num)

num += 1

Loop While num <= 5

This will print numbers 1 through 5.

5. Do...Loop Until:
Definition: Executes a block of statements and then continues to do so until a condition
becomes true.

Example:

vb.net

Dim num As Integer = 1

Do

Console.WriteLine(num)

num += 1

Loop Until num > 5

This will print numbers 1 through 5.

Arrays:

Definition: An array is a data structure that allows you to store multiple values of the
same type in a single variable. These values can be retrieved by referring to an index
number.

Example:

vb.net

Dim numbers(4) As Integer ' Declare an array that can hold 5 integers (0-4 inclusive)
numbers(0) = 1

numbers(1) = 2

Types of Array:

a. Single-dimensional Array:

Definition: This type of array represents a one-dimensional structure where data is


organized in a linear form.

Example:

vb.net

Dim names(2) As String

names(0) = "Alice"

names(1) = "Bob"

names(2) = "Charlie"

b. Multi-dimensional Array:

Definition: These arrays have more than one dimension, often visualized as matrices,
tables, or other geometric structures.

Example:

vb.net
Dim matrix(2, 2) As Integer ' 3x3 matrix

matrix(0, 0) = 1

matrix(0, 1) = 2

matrix(1, 0) = 3

c. Jagged Arrays:

Definition: An array of arrays, where each array can be of a different size. It's called
"jagged" because it doesn't have a consistent structure like a multi-dimensional array.

Example:

vb.net

Dim jaggedArray()() As Integer = New Integer(2)() {}

jaggedArray(0) = New Integer() {1, 2, 3}

jaggedArray(1) = New Integer() {4, 5}

In the above example, the first inner array has three elements, while the second one has
two.

2. Structures:
Definition: A structure (or Struct) in VB.NET is a composite data type, meaning it groups
together variables of different data types under a single name. Unlike classes,
structures are value types, so they are stored on the stack rather than the heap.

Example:

vb.net

Structure Book

Public Title As String

Public Author As String

Public Pages As Integer

End Structure

Dim myBook As Book

myBook.Title = "VB.NET Fundamentals"

myBook.Author = "John Doe"

myBook.Pages = 500

Here, the Book structure groups together a title, author, and page count into a single
cohesive unit.
Collections:

Definition: Collections are classes designed to store and manage groups of related
objects. They can be indexed and iterated upon and provide various methods to add,
remove, or find items.

Types of Collections:

a. ArrayList:

Definition: A dynamic array that can hold items of any type. It automatically resizes itself
when needed.

Example:

vb.net

Dim list As New ArrayList()

list.Add("Hello")

list.Add(123)

b. Hashtable:

Definition: Represents a collection of key/value pairs that are organized based on the
hash code of the key. It allows quick access to values based on their keys.

Example:
vb.net

Dim hash As New Hashtable()

hash("Name") = "John"

hash("Age") = 25

c. Stack:

Definition: Represents a last-in, first-out (LIFO) collection of objects. You "push" items
onto the stack and "pop" them off.

Example:

vb.net

Dim stack As New Stack()

stack.Push("First")

stack.Push("Second")

Dim top = stack.Pop() ' Returns "Second"

d. Queue:

Definition: Represents a first-in, first-out (FIFO) collection of objects. You "enqueue"


items at the end and "dequeue" them from the front.
Example:

vb.net

Dim queue As New Queue()

queue.Enqueue("First")

queue.Enqueue("Second")

Dim front = queue.Dequeue() ' Returns "First"

Generic Collections (part of System.Collections.Generic namespace):

a. List(Of T):

Definition: A strongly-typed dynamic array. It's similar to ArrayList but ensures type
safety since all items are of a specific type (T).

Example:

vb.net

Dim list As New List(Of Integer)()

list.Add(1)

list.Add(2)

b. Dictionary(Of TKey, TValue):


Definition: A collection of keys and values. It's a strongly-typed and more efficient
version of Hashtable.

Example:

vb.net

Dim dict As New Dictionary(Of String, Integer)()

dict("Apple") = 5

dict("Banana") = 10

c. Stack(Of T) and Queue(Of T):

Definition: Generic versions of the Stack and Queue classes which are strongly typed.

Example:

vb.net

Dim stack As New Stack(Of String)()

stack.Push("Hello")

Dim queue As New Queue(Of String)()

queue.Enqueue("Hello")
Procedures: Subroutines and Functions, Passing Arguments

In VB.NET, procedures are blocks of code that perform specific tasks or operations.
There are two main types of procedures: subroutines and functions. Subroutines do not
return a value, while functions return a value. When you want to pass data to a
procedure or function, you can do so using arguments.

Here's a breakdown of how to define and use subroutines and functions, as well as how
to pass arguments in VB.NET:

Subroutines:

● Subroutines are defined using the Sub keyword.


● They do not return a value (or return Sub).
● You can pass arguments to subroutines to provide input data.

Example of defining a subroutine:

vb.net

Sub MySubroutine(ByVal arg1 As Integer, ByVal arg2 As String)

' Perform some actions using arg1 and arg2

End Sub

Example of calling a subroutine:

vb.net

Dim x As Integer = 5
Dim y As String = "Hello"

MySubroutine(x, y)

Functions:

● Functions are defined using the Function keyword.


● They return a value using the Return statement.
● You can pass arguments to functions and use them to calculate the return value.

Example of defining a function:

vb.net

Function AddNumbers(ByVal num1 As Integer, ByVal num2 As Integer) As Integer

Dim result As Integer = num1 + num2

Return result

End Function

Example of calling a function:

vb.net

Dim a As Integer = 10

Dim b As Integer = 20

Dim sum As Integer = AddNumbers(a, b)

Console.WriteLine("Sum: " & sum)

Passing Arguments:
● When passing arguments to a procedure or function, you specify the argument
names and their data types.
● You can use the ByVal keyword to pass arguments by value (a copy of the data is
passed), or the ByRef keyword to pass arguments by reference (the actual data is
passed).
● ByVal is the default and is used when you don't specify ByVal or ByRef.

Example of passing arguments by value:

vb.net

Sub ChangeValue(ByVal num As Integer)

num = num + 1

End Sub

Dim x As Integer = 5

ChangeValue(x)

Console.WriteLine(x) ' Outputs 5 (unchanged)

Example of passing arguments by reference:

vb.net

Sub ChangeValue(ByRef num As Integer)

num = num + 1

End Sub

Dim x As Integer = 5

ChangeValue(x)

Console.WriteLine(x) ' Outputs 6 (changed)


Optional Arguments:

Optional arguments allow you to define parameters for procedures (subroutines or


functions) that don't require values to be passed when calling the procedure. This can
make your code more flexible and readable because you can provide default values for
parameters while still allowing callers to override them if needed.

To define an optional argument in VB.NET, you use the Optional keyword when declaring
a parameter. You can also provide a default value for the parameter.

Example of a function with an optional argument:

vb.net

Function CalculateTotal(ByVal price As Decimal, Optional ByVal quantity As Integer = 1)


As Decimal

Return price * quantity

End Function

When calling this function, you can provide a value for quantity if you want to override
the default:

vb.net

Dim total1 As Decimal = CalculateTotal(10.0) ' Uses the default quantity of 1

Dim total2 As Decimal = CalculateTotal(15.0, 3) ' Overrides the quantity with 3

Structures:
Structures in VB.NET are used to define custom data types that group related fields
together. They are similar to classes but have some differences. Structures are value
types, which means they are copied when assigned to a new variable or passed as
function arguments. They are often used for lightweight objects that don't require
inheritance or complex behavior.

Here's how you can define a structure in VB.NET:

vb.net

Structure Point

Public X As Integer

Public Y As Integer

End Structure

You might also like