Lecture 1 / 12
Lecture 01 ยท Fundamentals

Introduction to Visual Basic .NET & Setup

Beginner ~50 min

What is Visual Basic .NET?

Visual Basic .NET (VB.NET) is a modern, object-oriented programming language from Microsoft. It is easy to learn, highly productive, and tightly integrated with the .NET ecosystem. It is widely used for Windows desktop applications, business tools, and enterprise software.

VB.NET was designed to help developers create applications quickly using simple and readable syntax. It combines the simplicity of traditional Visual Basic with the power of the modern .NET framework.

VB.NET supports object-oriented programming concepts such as classes, inheritance, encapsulation, and polymorphism, making it suitable for both beginners and professional developers.

Why Learn VB.NET?

  • Very readable, English-like syntax
  • Rapid Application Development (RAD)
  • Excellent Windows Forms and WPF support
  • Seamless integration with C# and the .NET platform
  • Strong support from Microsoft
  • Great for desktop and business applications
  • Easy transition into other .NET languages

Where is VB.NET Used?

  • Windows desktop applications
  • Business management systems
  • Database-driven software
  • Enterprise tools and utilities
  • Automation applications
  • Educational and academic projects

Understanding the .NET Framework

The .NET framework is a software development platform created by Microsoft that provides tools, libraries, and runtime support for building applications.

VB.NET runs on the .NET platform, which provides:

  • Built-in libraries and APIs
  • Memory management through garbage collection
  • Security and exception handling
  • Support for multiple programming languages

Languages such as VB.NET and C# can work together because they use the same .NET framework.

Setup

Install Visual Studio Community (free) from visualstudio.microsoft.com. Choose the ".NET desktop development" workload.

Visual Studio is Microsoft's official Integrated Development Environment (IDE) used for writing, testing, debugging, and running VB.NET applications.

Steps to Install Visual Studio

  1. Download Visual Studio Community Edition
  2. Run the installer
  3. Select the ".NET desktop development" workload
  4. Complete the installation process
  5. Launch Visual Studio

Creating Your First VB.NET Project

  1. Open Visual Studio
  2. Click Create a new project
  3. Select Console App (.NET)
  4. Choose Visual Basic as the language
  5. Enter a project name
  6. Click Create

Visual Studio automatically generates starter code for your first application.

Understanding the First Program

Module1.vb
Module Module1
    Sub Main()
        Console.WriteLine("Hello, Visual Basic .NET Mastery!")
        Console.ReadKey()
    End Sub
End Module
Output
Hello, Visual Basic .NET Mastery!

Code Explanation

  • Module defines a program container.
  • Sub Main() is the starting point of the application.
  • Console.WriteLine() displays output on the screen.
  • Console.ReadKey() waits for a key press before closing the program.
  • End Sub marks the end of the procedure.

๐Ÿ’ป Try It Yourself - Multi-Language Compiler

Practice Visual Basic and many other programming languages right here in your browser! Switch between languages, modify the code, and click "Run" to see results instantly.

๐Ÿ’ก Practice Tips:

  • Switch to Visual Basic in the language selector and try Windows form examples
  • Experiment with VB.NET's event-driven programming and .NET framework features
  • Try other .NET languages like C#, F#, or compare with desktop development concepts
  • Use the "Load Example" button to see Visual Basic-specific code samples
  • Use Ctrl+Enter to quickly run your code

Running a Program

You can run VB.NET programs using the following methods:

  • Press F5 to run with debugging
  • Press Ctrl + F5 to run without debugging
  • Click the Start button in Visual Studio

Debugging helps developers identify and fix errors in programs.

Console Applications

A console application displays output in a command-line window.

Console applications are ideal for beginners because they focus on programming logic without requiring graphical interfaces.

ConsoleExample.vb
Module Program
    Sub Main()

        Console.WriteLine("Welcome to VB.NET")
        Console.WriteLine("Learning programming is fun!")

        Console.ReadKey()

    End Sub
End Module

Important Notes for Beginners

  • VB.NET keywords are not case-sensitive.
  • Always save projects in organized folders.
  • Use meaningful project and file names.
  • Practice typing programs manually to improve learning.
  • Read error messages carefully while debugging.

Common VB.NET Keywords

Keyword Description
Module Defines a module container
Sub Defines a procedure
End Marks the end of a block
Console.WriteLine() Displays output
Console.ReadKey() Waits for keyboard input
๐ŸŽฏ Exercise 1.1

Create a new Console Application in Visual Studio. Modify it to print your name and run the project (F5).

๐ŸŽฏ Exercise 1.2

Create a program that displays your city, favorite subject, and hobby using multiple Console.WriteLine() statements.

๐ŸŽฏ Exercise 1.3

Practice creating and running multiple console applications in Visual Studio.

Lecture 02 ยท Fundamentals

Variables & Data Types

Beginner ~45 min

What are Variables?

Variables are used to store data in memory while a program is running. They allow programmers to save values and use them later in calculations, conditions, and other operations.

In VB.NET, every variable has:

  • A name
  • A data type
  • A stored value

Variables make programs dynamic because values can change during execution.

Declaring Variables

In VB.NET, variables are declared using the Dim keyword.

Dim age As Integer
Dim name As String
Dim salary As Double

Here:

  • age stores whole numbers.
  • name stores text.
  • salary stores decimal numbers.

Assigning Values to Variables

After declaring variables, values can be assigned using the assignment operator =.

Dim age As Integer
age = 21

Dim city As String
city = "London"

You can also declare and assign values in a single line.

Dim marks As Integer = 95
Dim studentName As String = "Alex"

Common Data Types in VB.NET

VB.NET provides different data types for storing different kinds of information.

Data Type Description Example
Integer Stores whole numbers 10
Double Stores decimal numbers 12.5
String Stores text "Hello"
Boolean Stores True or False True
Char Stores a single character "A"

Displaying Variable Values

Use Console.WriteLine() to display variable values on the screen.

Dim name As String = "John"
Dim age As Integer = 22

Console.WriteLine(name)
Console.WriteLine(age)
Output
John 22

Combining Text and Variables

VB.NET allows text and variables to be combined using the & operator.

Dim name As String = "Emma"
Dim marks As Integer = 90

Console.WriteLine("Student Name: " & name)
Console.WriteLine("Marks: " & marks)
Output
Student Name: Emma Marks: 90

Rules for Naming Variables

  • Variable names must begin with a letter.
  • Spaces are not allowed.
  • Special characters are not allowed except underscores.
  • Use meaningful variable names.
  • VB.NET keywords should not be used as variable names.
' Valid variable names
Dim totalMarks As Integer
Dim student_name As String

' Invalid variable names
' Dim 2marks As Integer
' Dim student name As String

Understanding Constants

Constants store fixed values that cannot be changed during program execution.

Const PI As Double = 3.14159

Constants improve readability and prevent accidental value changes.

User Input in VB.NET

Programs can accept input from users using Console.ReadLine().

Dim username As String

Console.Write("Enter your name: ")
username = Console.ReadLine()

Console.WriteLine("Hello " & username)

Console.ReadLine() reads text entered by the user.

Type Conversion

Sometimes data must be converted from one type to another.

Dim number As Integer
number = Convert.ToInt32("100")

Console.WriteLine(number)

The Convert class helps convert values between data types.

Variable Scope

The scope of a variable determines where it can be accessed in a program.

  • Local variables exist only inside procedures.
  • Global variables can be accessed throughout the module.
Module Module1

    Dim globalValue As Integer = 100

    Sub Main()

        Dim localValue As Integer = 50

        Console.WriteLine(globalValue)
        Console.WriteLine(localValue)

    End Sub

End Module

Important Notes for Beginners

  • Always initialize variables before using them.
  • Use meaningful names for better readability.
  • Choose appropriate data types for storing values.
  • Constants are useful for fixed values.
  • Practice using user input and output frequently.
๐ŸŽฏ Exercise 2.1

Create variables to store your name, age, and favorite color. Display them using Console.WriteLine().

๐ŸŽฏ Exercise 2.2

Create a program that accepts user input for marks and displays the result.

๐ŸŽฏ Exercise 2.3

Create constants for PI and gravity and display their values.

๐ŸŽฏ Exercise 2.4

Create variables using different data types such as Integer, Double, String, and Boolean.

Lecture 03 ยท Fundamentals

Operators & Expressions

Beginner ~50 min

What are Operators?

Operators are symbols used to perform operations on variables and values. VB.NET provides different types of operators for mathematical calculations, comparisons, and logical decisions.

Operators are commonly used in:

  • Calculations
  • Conditions
  • Loops
  • Decision-making statements

What are Expressions?

An expression is a combination of variables, values, and operators that produces a result.

Dim result As Integer

result = 10 + 5

In this example:

  • 10 + 5 is an expression.
  • The expression evaluates to 15.

Arithmetic Operators

Arithmetic operators are used for mathematical calculations.

Operator Description Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
\ Integer Division 10 \ 3
Mod Returns remainder 10 Mod 3
Dim a As Integer = 10
Dim b As Integer = 3

Console.WriteLine(a + b)
Console.WriteLine(a - b)
Console.WriteLine(a * b)
Console.WriteLine(a / b)
Console.WriteLine(a \ b)
Console.WriteLine(a Mod b)
Output
13 7 30 3.333333 3 1

Assignment Operators

Assignment operators are used to assign values to variables.

Operator Description
= Assigns a value
+= Add and assign
-= Subtract and assign
Dim x As Integer = 10

x += 5
Console.WriteLine(x)

x -= 2
Console.WriteLine(x)

Comparison Operators

Comparison operators compare two values and return either True or False.

Operator Description
= Equal to
<> Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Dim num1 As Integer = 10
Dim num2 As Integer = 20

Console.WriteLine(num1 = num2)
Console.WriteLine(num1 < num2)
Console.WriteLine(num1 > num2)
Output
False True False

Logical Operators

Logical operators combine multiple conditions.

Operator Description
And True if both conditions are true
Or True if at least one condition is true
Not Reverses the logical result
Dim age As Integer = 25

Console.WriteLine(age > 18 And age < 60)
Console.WriteLine(age < 18 Or age > 60)
Console.WriteLine(Not(age = 25))

String Concatenation

Strings can be combined using the & operator.

Dim firstName As String = "John"
Dim lastName As String = "Smith"

Dim fullName As String

fullName = firstName & " " & lastName

Console.WriteLine(fullName)
Output
John Smith

Operator Precedence

VB.NET follows precedence rules while evaluating expressions.

  1. Parentheses
  2. Exponentiation
  3. Multiplication and Division
  4. Addition and Subtraction
  5. Comparison Operators
  6. Logical Operators
Dim result1 As Integer = 2 + 3 * 4
Dim result2 As Integer = (2 + 3) * 4

Console.WriteLine(result1)
Console.WriteLine(result2)
Output
14 20

Parentheses improve readability and help avoid unexpected results.

Using Built-in Mathematical Functions

VB.NET provides built-in methods for mathematical calculations.

Console.WriteLine(Math.Sqrt(25))
Console.WriteLine(Math.Pow(2, 3))
Console.WriteLine(Math.Abs(-10))
Output
5 8 10
  • Math.Sqrt() calculates square roots.
  • Math.Pow() calculates powers.
  • Math.Abs() returns absolute values.

Important Notes for Beginners

  • Use parentheses to make expressions easier to understand.
  • Practice arithmetic and logical operations regularly.
  • Comparison operators return Boolean values.
  • Logical operators are important in conditions and loops.
  • Understand operator precedence to avoid errors.
๐ŸŽฏ Exercise 3.1

Create a program that performs addition, subtraction, multiplication, and division on two numbers.

๐ŸŽฏ Exercise 3.2

Use comparison operators to compare two integer values and display the results.

๐ŸŽฏ Exercise 3.3

Create expressions using parentheses and observe how operator precedence changes results.

๐ŸŽฏ Exercise 3.4

Create a program that combines first name and last name using string concatenation.

Lecture 04 ยท Fundamentals

Control Flow

Beginner ~45 min

What is Control Flow?

Control flow determines how a VB.NET program executes different parts of code based on conditions, decisions, and repetition. It controls the order in which statements are executed.

Without control flow, programs would execute every line sequentially without making decisions.

Control flow allows programs to:

  • Make decisions based on conditions
  • Repeat tasks automatically
  • Respond differently to user input
  • Control program execution efficiently

Conditional Statements

Conditional statements allow programs to execute specific code only when certain conditions are true.

The If Statement

The If statement checks a condition and executes code if the condition is true.

Dim age As Integer = 20

If age >= 18 Then
    Console.WriteLine("You are eligible to vote.")
End If

If the condition evaluates to True, the code inside the block executes.

If...Else Statement

The If...Else statement provides an alternative block of code when the condition is false.

Dim marks As Integer = 45

If marks >= 50 Then
    Console.WriteLine("Pass")
Else
    Console.WriteLine("Fail")
End If
Output
Fail

If...ElseIf...Else Statement

Use ElseIf when multiple conditions need to be checked.

Dim number As Integer = 0

If number > 0 Then
    Console.WriteLine("Positive")

ElseIf number < 0 Then
    Console.WriteLine("Negative")

Else
    Console.WriteLine("Zero")

End If

Conditions are checked from top to bottom until one becomes true.

Nested If Statements

An If statement can be placed inside another If statement.

Dim number As Integer = 8

If number > 0 Then

    If number Mod 2 = 0 Then
        Console.WriteLine("Positive Even Number")
    Else
        Console.WriteLine("Positive Odd Number")
    End If

End If

The Mod operator returns the remainder after division.

Select Case Statement

The Select Case statement is useful when comparing one variable against multiple possible values.

Dim day As Integer = 3

Select Case day

    Case 1
        Console.WriteLine("Monday")

    Case 2
        Console.WriteLine("Tuesday")

    Case 3
        Console.WriteLine("Wednesday")

    Case Else
        Console.WriteLine("Invalid Day")

End Select

Select Case improves readability when handling many possible options.

Introduction to Loops

Loops allow programs to repeat a block of code multiple times automatically.

VB.NET mainly provides:

  • For Loop
  • While Loop
  • Do While Loop

For Loop

A For loop is used when the number of repetitions is known.

For i As Integer = 1 To 5
    Console.WriteLine(i)
Next
Output
1 2 3 4 5

For Loop with Step

The Step keyword changes the increment value.

For i As Integer = 0 To 10 Step 2
    Console.WriteLine(i)
Next

While Loop

A While loop repeats while a condition remains true.

Dim x As Integer = 1

While x <= 5

    Console.WriteLine(x)
    x += 1

End While

Be careful because incorrect conditions may create infinite loops.

Do While Loop

The Do While loop executes code repeatedly while a condition is true.

Dim number As Integer = 1

Do While number <= 5

    Console.WriteLine(number)
    number += 1

Loop

Nested Loops

Loops can also be placed inside other loops.

For i As Integer = 1 To 3

    For j As Integer = 1 To 2

        Console.WriteLine(i & " " & j)

    Next

Next

Nested loops are commonly used in tables, patterns, and matrix-like operations.

Exit Statement

The Exit statement immediately stops a loop.

For i As Integer = 1 To 10

    If i = 5 Then
        Exit For
    End If

    Console.WriteLine(i)

Next

Continue Statement

The Continue statement skips the current iteration and moves to the next one.

For i As Integer = 1 To 5

    If i = 3 Then
        Continue For
    End If

    Console.WriteLine(i)

Next

In this example, the value 3 is skipped.

Important Notes for Beginners

  • Always close blocks correctly using End If, Next, or Loop.
  • Use indentation to improve readability.
  • For loops are best when repetitions are fixed.
  • While loops are useful when repetition depends on conditions.
  • Test conditions carefully to avoid infinite loops.
๐ŸŽฏ Exercise 4.1

Create a program that checks whether a number is positive, negative, or zero.

๐ŸŽฏ Exercise 4.2

Create a For loop that displays numbers from 1 to 20.

๐ŸŽฏ Exercise 4.3

Create a While loop that displays even numbers from 2 to 10.

๐ŸŽฏ Exercise 4.4

Use a Select Case statement to display the name of a month based on a number.

๐ŸŽฏ Exercise 4.5

Create a nested loop that displays multiplication tables from 1 to 5.

Lecture 05 ยท Fundamentals

Loops

Beginner ~50 min

What are Loops?

Loops are programming structures that allow a block of code to execute repeatedly until a condition becomes false. They help reduce repetitive code and make programs more efficient.

Loops are commonly used for:

  • Displaying repeated output
  • Processing collections of data
  • Performing calculations multiple times
  • Automating repetitive tasks

VB.NET provides several types of loops for different situations.

Types of Loops in VB.NET

  • For Loop
  • While Loop
  • Do While Loop
  • Do Until Loop
  • For Each Loop

For Loop

A For loop is used when the number of repetitions is known in advance.

For i As Integer = 1 To 5

    Console.WriteLine(i)

Next
Output
1 2 3 4 5

The loop variable automatically increases after each iteration.

For Loop with Step

The Step keyword controls the increment or decrement value.

For i As Integer = 0 To 10 Step 2

    Console.WriteLine(i)

Next
Output
0 2 4 6 8 10

Reverse Loop

A negative step value can create reverse loops.

For i As Integer = 5 To 1 Step -1

    Console.WriteLine(i)

Next

While Loop

A While loop repeats as long as the condition remains true.

Dim number As Integer = 1

While number <= 5

    Console.WriteLine(number)
    number += 1

End While

The condition is checked before executing the loop body.

Do While Loop

The Do While loop also repeats while a condition is true.

Dim x As Integer = 1

Do While x <= 5

    Console.WriteLine(x)
    x += 1

Loop

This loop behaves similarly to the While loop.

Do Until Loop

The Do Until loop continues until a condition becomes true.

Dim value As Integer = 1

Do Until value > 5

    Console.WriteLine(value)
    value += 1

Loop

The loop stops once the condition becomes true.

For Each Loop

The For Each loop is used to iterate through collections and arrays.

Dim numbers() As Integer = {1, 2, 3, 4, 5}

For Each num As Integer In numbers

    Console.WriteLine(num)

Next

For Each loops are simpler and safer when working with collections.

Nested Loops

Loops can be placed inside other loops. These are called nested loops.

For i As Integer = 1 To 3

    For j As Integer = 1 To 2

        Console.WriteLine(i & " " & j)

    Next

Next

Nested loops are useful for patterns, tables, and matrix-style operations.

Exit Statements

The Exit statement immediately terminates a loop.

For i As Integer = 1 To 10

    If i = 5 Then
        Exit For
    End If

    Console.WriteLine(i)

Next

The loop stops completely when the condition is met.

Continue Statements

The Continue statement skips the current iteration and moves to the next one.

For i As Integer = 1 To 5

    If i = 3 Then
        Continue For
    End If

    Console.WriteLine(i)

Next
Output
1 2 4 5

In this example, the value 3 is skipped.

Infinite Loops

An infinite loop occurs when the loop condition never becomes false.

' Infinite loop example

While True

    Console.WriteLine("Running forever")

End While

Infinite loops can freeze programs if not handled properly.

Looping Through Arrays

Loops are commonly used with arrays.

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

For Each fruit As String In fruits

    Console.WriteLine(fruit)

Next

Best Practices for Loops

  • Use meaningful loop variable names.
  • Avoid unnecessary nested loops.
  • Ensure loop conditions eventually become false.
  • Use For Each for collections whenever possible.
  • Indent loop code properly for readability.

Important Notes for Beginners

  • For loops are best for fixed repetitions.
  • While loops are useful when repetitions depend on conditions.
  • Nested loops increase complexity, so use them carefully.
  • Always test loop conditions carefully.
  • Practice loops regularly to improve problem-solving skills.
๐ŸŽฏ Exercise 5.1

Create a For loop that displays numbers from 1 to 50.

๐ŸŽฏ Exercise 5.2

Create a While loop that displays even numbers from 2 to 20.

๐ŸŽฏ Exercise 5.3

Create a multiplication table using nested loops.

๐ŸŽฏ Exercise 5.4

Create an array of names and display them using a For Each loop.

๐ŸŽฏ Exercise 5.5

Create a reverse counting program using a negative Step value.

Lecture 06 ยท Core Concepts

Procedures & Functions

Beginner ~45 min

Procedures and functions are essential building blocks in Visual Basic programming. They help organize code into reusable sections, making programs easier to read, maintain, and debug.

Instead of writing the same code repeatedly, developers can create procedures and functions that can be called whenever needed. This improves efficiency and reduces code duplication.

What are Procedures?

A procedure is a block of code that performs a specific task. In Visual Basic, procedures are commonly created using the Sub keyword.

Sub procedures do not return a value. They are mainly used for performing actions such as displaying messages, processing data, or handling user input.

Sub Procedures

sub.vb
Sub Greet(name As String)

    Console.WriteLine("Hello, " & name)

End Sub

Greet("Ahmed")

In this example:

  • Sub Greet defines a new procedure
  • name As String is a parameter
  • Console.WriteLine() displays output
  • Greet("Ahmed") calls the procedure

Output:

Hello, Ahmed

Why Use Procedures?

  • Reduce duplicate code
  • Improve program organization
  • Make debugging easier
  • Increase code reusability
  • Simplify large applications

Passing Parameters

Parameters allow information to be passed into procedures and functions. They make code flexible and reusable.

params.vb
Sub DisplayMessage(message As String)

    Console.WriteLine(message)

End Sub

DisplayMessage("Welcome to VB.NET")

What are Functions?

Functions are similar to procedures, but they return a value after performing calculations or processing data. Functions are declared using the Function keyword.

Functions

func.vb
Function Add(a As Integer, b As Integer) As Integer

    Return a + b

End Function

Dim total As Integer = Add(5, 3)  ' 8

In this example:

  • Add() is a function
  • a and b are parameters
  • As Integer defines the return type
  • Return sends the result back

Output:

8

Difference Between Sub and Function

Sub Procedure Function
Does not return a value Returns a value
Used for actions Used for calculations
Declared with Sub Declared with Function

Return Values

Functions return values using the Return keyword.

return.vb
Function Square(num As Integer) As Integer

    Return num * num

End Function

Console.WriteLine(Square(4))

Output:

16

Optional Parameters

Optional parameters allow arguments to be omitted when calling procedures or functions. Default values are used automatically.

Optional & ByRef

opt.vb
Sub Greet(Optional name As String = "World")

    Console.WriteLine("Hello, " & name)

End Sub

Sub Swap(ByRef a As Integer, ByRef b As Integer)

    Dim tmp = a
    a = b
    b = tmp

End Sub

In this example:

  • Optional allows a default parameter value
  • ByRef passes variables by reference
  • Changes made inside the procedure affect original variables

ByVal vs ByRef

Visual Basic supports two ways of passing parameters:

  • ByVal โ†’ Passes a copy of the value
  • ByRef โ†’ Passes the original variable reference
byval.vb
Sub ChangeValue(ByVal num As Integer)

    num = 100

End Sub

Changes inside a ByVal parameter do not affect the original variable.

Function Overloading

Visual Basic allows multiple functions with the same name but different parameter lists. This is called function overloading.

overload.vb
Function Multiply(a As Integer, b As Integer) As Integer

    Return a * b

End Function

Function Multiply(a As Double, b As Double) As Double

    Return a * b

End Function

Recursive Functions

A recursive function calls itself repeatedly until a condition is met. Recursion is useful for mathematical and algorithmic problems.

factorial.vb
Function Factorial(n As Integer) As Integer

    If n = 0 Then
        Return 1
    End If

    Return n * Factorial(n - 1)

End Function

Variable Scope

Scope determines where variables can be accessed inside a program.

  • Local Variables โ†’ Accessible only inside procedures
  • Global Variables โ†’ Accessible throughout the program
scope.vb
Dim globalVar As Integer = 10

Sub Test()

    Dim localVar As Integer = 5

End Sub

Error Handling in Functions

Functions and procedures should handle invalid input properly to avoid crashes.

errors.vb
Try

    Dim result = 10 / 0

Catch ex As Exception

    Console.WriteLine("Error occurred")

End Try

Advantages of Functions & Procedures

  • Improve code reusability
  • Reduce program complexity
  • Make code easier to maintain
  • Increase readability
  • Simplify debugging and testing

Real-World Applications

  • Banking systems
  • Game development
  • Desktop applications
  • Inventory management software
  • Student management systems
  • Scientific applications

Best Practices

  • Use meaningful procedure and function names
  • Keep functions short and focused
  • Avoid duplicate code
  • Use comments for complex logic
  • Validate user input properly
Practice

Write functions to compute factorial, GCD, and Fibonacci numbers.

Try adding:

  • User input handling
  • Error checking
  • Recursive implementations
  • Loop-based solutions

Summary

In this lecture, we learned how procedures and functions work in Visual Basic. We explored Sub procedures, functions, parameters, optional arguments, recursion, and parameter passing methods.

Functions and procedures are essential programming concepts that improve organization, reusability, and maintainability in software development.

Lecture 07 ยท Core Concepts

Arrays & Collections

Beginner ~45 min

Arrays and collections are essential data structures in Visual Basic programming. They allow developers to store, organize, and manage multiple values efficiently.

Instead of creating separate variables for every piece of data, arrays and collections group related data together. This makes programs more scalable, readable, and easier to maintain.

Introduction to Arrays

An array is a collection of values stored inside a single variable. All elements inside an array usually share the same data type.

Arrays are useful when working with lists of numbers, names, scores, products, or other grouped data.

Arrays

arr.vb
Dim nums(4) As Integer  ' 0-4 = 5 elements

nums(0) = 10

Dim names() As String = {"Aman", "Rahul", "Arjun"}

For Each n As String In names

    Console.WriteLine(n)

Next

In this example:

  • nums(4) creates an array with 5 elements
  • Array indexing starts from 0
  • names() initializes a string array
  • For Each loops through all elements

Output:

Aman
Rahul
Arjun

Why Use Arrays?

  • Store multiple values efficiently
  • Reduce repetitive variables
  • Simplify loops and processing
  • Improve code organization
  • Useful for large datasets

Accessing Array Elements

Array elements are accessed using indexes inside parentheses.

access.vb
Dim fruits() As String = {"Apple", "Banana", "Orange"}

Console.WriteLine(fruits(1))

Output:

Banana

Here, fruits(1) accesses the second element because indexing begins at 0.

Modifying Array Values

Array elements can be updated by assigning new values.

modify.vb
Dim scores() As Integer = {50, 60, 70}

scores(1) = 95

Console.WriteLine(scores(1))

Looping Through Arrays

Loops are commonly used with arrays to process all elements efficiently.

loop.vb
Dim nums() As Integer = {1, 2, 3, 4, 5}

For i As Integer = 0 To nums.Length - 1

    Console.WriteLine(nums(i))

Next

The Length property returns the total number of elements in the array.

Multi-Dimensional Arrays

Visual Basic supports arrays with multiple dimensions such as rows and columns.

multi.vb
Dim matrix(1, 1) As Integer

matrix(0, 0) = 10
matrix(0, 1) = 20

matrix(1, 0) = 30
matrix(1, 1) = 40

Multi-dimensional arrays are useful for tables, matrices, and grid-based systems.

Introduction to Collections

Collections are advanced data structures that provide more flexibility than arrays. Unlike arrays, collections can dynamically grow and shrink during program execution.

List(Of T)

The List(Of T) collection stores dynamic lists of data. It is one of the most commonly used collection types in VB.NET.

list.vb
Dim items As New List(Of String)

items.Add("Apple")

items.Add("Banana")

items.Remove("Apple")

Console.WriteLine(items.Count)

In this example:

  • Add() inserts new items
  • Remove() deletes items
  • Count returns total items

Output:

1

Advantages of List(Of T)

  • Dynamic resizing
  • Easy insertion and removal
  • Powerful built-in methods
  • Efficient data handling
  • Flexible compared to arrays

Looping Through Lists

foreach.vb
Dim colors As New List(Of String)

colors.Add("Red")
colors.Add("Blue")
colors.Add("Green")

For Each c In colors

    Console.WriteLine(c)

Next

Dictionary

A Dictionary stores data as key-value pairs. It allows fast searching and retrieval using keys.

dict.vb
Dim ages As New Dictionary(Of String, Integer)

ages("Ahmed") = 25

ages("Sara") = 30

For Each kvp In ages

    Console.WriteLine($"{kvp.Key}: {kvp.Value}")

Next

In this example:

  • Ahmed and Sara are keys
  • 25 and 30 are values
  • kvp.Key accesses the key
  • kvp.Value accesses the value

Accessing Dictionary Values

lookup.vb
Console.WriteLine(ages("Ahmed"))

Output:

25

Checking Dictionary Keys

The ContainsKey() method checks whether a key exists.

contains.vb
If ages.ContainsKey("Sara") Then

    Console.WriteLine("Found")

End If

Choosing Between Arrays & Collections

Arrays Collections
Fixed size Dynamic size
Faster for simple data More flexible
Less memory overhead More built-in features

Real-World Applications

  • Student management systems
  • Phone books and contact lists
  • Inventory systems
  • Game scoreboards
  • Banking applications
  • Shopping cart systems

Best Practices

  • Use arrays for fixed-size data
  • Use lists for dynamic data
  • Use dictionaries for fast key-based lookup
  • Choose meaningful variable names
  • Validate indexes before accessing elements
Practice

Build a phone book using Dictionary(Of String, String).

Try adding:

  • Add new contacts
  • Search contacts by name
  • Delete contacts
  • Display all saved entries

Summary

In this lecture, we learned about arrays and collections in Visual Basic. We explored arrays, lists, dictionaries, looping techniques, and data storage methods.

Arrays and collections are essential tools for organizing and processing data efficiently in modern applications.

Lecture 07 ยท Core Concepts

Arrays & Collections

Beginner ~45 min

Arrays and collections are essential data structures in Visual Basic programming. They allow developers to store, organize, and manage multiple values efficiently.

Instead of creating separate variables for every piece of data, arrays and collections group related data together. This makes programs more scalable, readable, and easier to maintain.

Introduction to Arrays

An array is a collection of values stored inside a single variable. All elements inside an array usually share the same data type.

Arrays are useful when working with lists of numbers, names, scores, products, or other grouped data.

Arrays

arr.vb
Dim nums(4) As Integer  ' 0-4 = 5 elements

nums(0) = 10

Dim names() As String = {"Aman", "Rahul", "Arjun"}

For Each n As String In names

    Console.WriteLine(n)

Next

In this example:

  • nums(4) creates an array with 5 elements
  • Array indexing starts from 0
  • names() initializes a string array
  • For Each loops through all elements

Output:

Aman
Rahul
Arjun

Why Use Arrays?

  • Store multiple values efficiently
  • Reduce repetitive variables
  • Simplify loops and processing
  • Improve code organization
  • Useful for large datasets

Accessing Array Elements

Array elements are accessed using indexes inside parentheses.

access.vb
Dim fruits() As String = {"Apple", "Banana", "Orange"}

Console.WriteLine(fruits(1))

Output:

Banana

Here, fruits(1) accesses the second element because indexing begins at 0.

Modifying Array Values

Array elements can be updated by assigning new values.

modify.vb
Dim scores() As Integer = {50, 60, 70}

scores(1) = 95

Console.WriteLine(scores(1))

Looping Through Arrays

Loops are commonly used with arrays to process all elements efficiently.

loop.vb
Dim nums() As Integer = {1, 2, 3, 4, 5}

For i As Integer = 0 To nums.Length - 1

    Console.WriteLine(nums(i))

Next

The Length property returns the total number of elements in the array.

Multi-Dimensional Arrays

Visual Basic supports arrays with multiple dimensions such as rows and columns.

multi.vb
Dim matrix(1, 1) As Integer

matrix(0, 0) = 10
matrix(0, 1) = 20

matrix(1, 0) = 30
matrix(1, 1) = 40

Multi-dimensional arrays are useful for tables, matrices, and grid-based systems.

Introduction to Collections

Collections are advanced data structures that provide more flexibility than arrays. Unlike arrays, collections can dynamically grow and shrink during program execution.

List(Of T)

The List(Of T) collection stores dynamic lists of data. It is one of the most commonly used collection types in VB.NET.

list.vb
Dim items As New List(Of String)

items.Add("Apple")

items.Add("Banana")

items.Remove("Apple")

Console.WriteLine(items.Count)

In this example:

  • Add() inserts new items
  • Remove() deletes items
  • Count returns total items

Output:

1

Advantages of List(Of T)

  • Dynamic resizing
  • Easy insertion and removal
  • Powerful built-in methods
  • Efficient data handling
  • Flexible compared to arrays

Looping Through Lists

foreach.vb
Dim colors As New List(Of String)

colors.Add("Red")
colors.Add("Blue")
colors.Add("Green")

For Each c In colors

    Console.WriteLine(c)

Next

Dictionary

A Dictionary stores data as key-value pairs. It allows fast searching and retrieval using keys.

dict.vb
Dim ages As New Dictionary(Of String, Integer)

ages("Ahmed") = 25

ages("Sara") = 30

For Each kvp In ages

    Console.WriteLine($"{kvp.Key}: {kvp.Value}")

Next

In this example:

  • Ahmed and Sara are keys
  • 25 and 30 are values
  • kvp.Key accesses the key
  • kvp.Value accesses the value

Accessing Dictionary Values

lookup.vb
Console.WriteLine(ages("Ahmed"))

Output:

25

Checking Dictionary Keys

The ContainsKey() method checks whether a key exists.

contains.vb
If ages.ContainsKey("Sara") Then

    Console.WriteLine("Found")

End If

Choosing Between Arrays & Collections

Arrays Collections
Fixed size Dynamic size
Faster for simple data More flexible
Less memory overhead More built-in features

Real-World Applications

  • Student management systems
  • Phone books and contact lists
  • Inventory systems
  • Game scoreboards
  • Banking applications
  • Shopping cart systems

Best Practices

  • Use arrays for fixed-size data
  • Use lists for dynamic data
  • Use dictionaries for fast key-based lookup
  • Choose meaningful variable names
  • Validate indexes before accessing elements
Practice

Build a phone book using Dictionary(Of String, String).

Try adding:

  • Add new contacts
  • Search contacts by name
  • Delete contacts
  • Display all saved entries

Summary

In this lecture, we learned about arrays and collections in Visual Basic. We explored arrays, lists, dictionaries, looping techniques, and data storage methods.

Arrays and collections are essential tools for organizing and processing data efficiently in modern applications.

Lecture 09 ยท Core Concepts

Exception Handling

Intermediate ~45 min

Exception handling is a mechanism used to detect and manage runtime errors in a program. Instead of crashing the application, exception handling allows developers to respond to errors gracefully.

Errors can occur for many reasons such as invalid user input, missing files, network failures, or mathematical mistakes. VB.NET provides powerful tools for handling these situations safely.

What is an Exception?

An exception is an unexpected problem that occurs while a program is running. When an exception occurs, normal program execution stops unless the error is handled properly.

Common exceptions include:

  • Division by zero
  • Invalid file paths
  • Incorrect data formats
  • Array index out of range
  • Null reference errors

Why Exception Handling is Important

  • Prevents application crashes
  • Improves user experience
  • Helps identify bugs
  • Protects important data
  • Makes programs more reliable

Try-Catch-Finally

VB.NET handles exceptions using the Try, Catch, and Finally blocks.

try.vb
Try

    Dim x = Integer.Parse("abc")

Catch ex As FormatException

    Console.WriteLine("Bad format: " & ex.Message)

Catch ex As Exception

    Console.WriteLine("Error: " & ex.Message)

Finally

    Console.WriteLine("Cleanup done.")

End Try

In this example:

  • Try contains risky code
  • Catch handles exceptions
  • FormatException handles invalid number formats
  • Finally executes whether an error occurs or not

Output:

Bad format: Input string was not in a correct format.
Cleanup done.

Understanding Try Block

The Try block contains code that may generate exceptions during execution.

tryonly.vb
Try

    Dim result = 10 / 0

Catch ex As Exception

    Console.WriteLine(ex.Message)

End Try

If an exception occurs inside the Try block, program control immediately moves to the appropriate Catch block.

Multiple Catch Blocks

Programs can use multiple catch blocks to handle different exception types separately.

multi.vb
Try

    Dim nums(2) As Integer

    Console.WriteLine(nums(5))

Catch ex As IndexOutOfRangeException

    Console.WriteLine("Invalid index")

Catch ex As Exception

    Console.WriteLine("General error")

End Try

Specific exceptions should always be placed before general exceptions.

The Finally Block

The Finally block always executes regardless of whether an exception occurs. It is commonly used for cleanup operations.

finally.vb
Try

    Console.WriteLine("Program running")

Finally

    Console.WriteLine("Resources released")

End Try

Typical uses of Finally include:

  • Closing files
  • Releasing database connections
  • Cleaning temporary resources
  • Saving logs

Common Exception Types

Exception Description
FormatException Invalid data format
DivideByZeroException Division by zero
FileNotFoundException Missing file
IndexOutOfRangeException Invalid array index
NullReferenceException Using null objects

Throwing Exceptions

Developers can manually generate exceptions using the Throw keyword.

throwbasic.vb
Dim age As Integer = -5

If age < 0 Then

    Throw New Exception("Age cannot be negative")

End If

Throw Custom Exception

Custom exceptions help create more meaningful and application-specific error handling.

throw.vb
Class InsufficientFundsException

    Inherits Exception

    Sub New(msg As String)

        MyBase.New(msg)

    End Sub

End Class

If balance < amount Then

    Throw New InsufficientFundsException("Not enough money!")

End If

In this example:

  • InsufficientFundsException is a custom exception class
  • Inherits Exception extends the base Exception class
  • Throw generates the custom error

Using Message Property

The Message property provides detailed information about an exception.

message.vb
Catch ex As Exception

    Console.WriteLine(ex.Message)

End Catch

Error Logging

Applications often log exceptions into files for debugging and maintenance.

log.vb
Catch ex As Exception

    File.AppendAllText(
        "errors.txt",
        ex.Message & vbCrLf
    )

End Catch

Nested Exception Handling

Exception handling blocks can also be nested inside each other.

nested.vb
Try

    Try

        Dim x = 10 / 0

    Catch ex As DivideByZeroException

        Console.WriteLine("Math error")

    End Try

Catch ex As Exception

    Console.WriteLine("Outer error")

End Try

Best Practices for Exception Handling

  • Handle only expected exceptions
  • Use specific exception types when possible
  • Avoid empty catch blocks
  • Log important errors
  • Use Finally for cleanup tasks
  • Do not overuse exceptions for normal logic

Real-World Applications

  • Banking software
  • Web applications
  • Database systems
  • Game development
  • Desktop applications
  • Cloud services

Advantages of Exception Handling

  • Improves application stability
  • Provides better debugging support
  • Prevents sudden crashes
  • Improves software reliability
  • Creates safer applications
Practice

Wrap a file-read operation in try-catch handling FileNotFound and IOException.

Try adding:

  • Custom error messages
  • Error logging to a file
  • User input validation
  • Finally block cleanup operations

Summary

In this lecture, we learned how exception handling works in VB.NET using Try, Catch, Finally, and Throw statements.

We explored built-in exceptions, custom exceptions, error logging, nested handling, and best practices for building reliable applications.

Exception handling is a critical skill that helps developers create stable and professional software systems.

Lecture 10 ยท OOP

Classes & Objects

Intermediate~45 min

Defining a Class

person.vb
Class Person
    Public Property Name As String
    Public Property Age As Integer
    Sub New(n As String, a As Integer)
        Name = n : Age = a
    End Sub
    Sub Greet()
        Console.WriteLine($"Hi, I'm {Name}")
    End Sub
End Class

Dim p As New Person("Ahmed", 25)
p.Greet()

Read-Only Properties

readonly.vb
Class Circle
    Public Property Radius As Double
    Public ReadOnly Property Area As Double
        Get
            Return Math.PI * Radius * Radius
        End Get
    End Property
End Class
Practice

Create a BankAccount class with Deposit, Withdraw, and Balance.

Lecture 11 ยท OOP

Inheritance & Polymorphism

Intermediate~45 min

Inheritance

inherit.vb
Class Animal
    Public Overridable Sub Speak()
        Console.WriteLine("...")
    End Sub
End Class

Class Dog
    Inherits Animal
    Public Overrides Sub Speak()
        Console.WriteLine("Woof!")
    End Sub
End Class

Abstract / MustInherit

abstract.vb
MustInherit Class Shape
    Public MustOverride Function Area() As Double
End Class

Class Square
    Inherits Shape
    Public Property Side As Double
    Public Overrides Function Area() As Double
        Return Side * Side
    End Function
End Class
Practice

Create Shape, Circle, Rectangle classes using inheritance and polymorphism.

Lecture 12 ยท OOP

Interfaces & Generics

Intermediate~45 min

Interface

iface.vb
Interface IPrintable
    Sub Print()
End Interface

Class Document
    Implements IPrintable
    Public Sub Print() Implements IPrintable.Print
        Console.WriteLine("Printing doc...")
    End Sub
End Class

Generic Class

generic.vb
Class Stack(Of T)
    Private items As New List(Of T)
    Sub Push(x As T) : items.Add(x) : End Sub
    Function Pop() As T
        Dim x = items(items.Count - 1)
        items.RemoveAt(items.Count - 1)
        Return x
    End Function
End Class

Dim s As New Stack(Of Integer)
s.Push(1) : s.Push(2)
Console.WriteLine(s.Pop()) ' 2
Practice

Build a generic Queue(Of T) class with Enqueue and Dequeue.

Lecture 13 ยท OOP

LINQ

Intermediate~45 min

Query Syntax

linq.vb
Dim nums = {1, 2, 3, 4, 5, 6}
Dim evens = From n In nums
            Where n Mod 2 = 0
            Select n
For Each e In evens : Console.WriteLine(e) : Next

Method Syntax

method.vb
Dim doubled = nums.Where(Function(n) n > 2) _
                  .Select(Function(n) n * 2) _
                  .ToList()
Dim total = nums.Sum()
Dim avg = nums.Average()
Dim sorted = nums.OrderByDescending(Function(n) n)

Group By

group.vb
Dim words = {"apple", "ant", "banana", "berry"}
Dim grouped = words.GroupBy(Function(w) w(0))
For Each g In grouped
    Console.WriteLine($"{g.Key}: {String.Join(",", g)}")
Next
Practice

Given a list of Person objects, use LINQ to find adults grouped by city.

Lecture 14 ยท Desktop Apps

Windows Forms & UI

Advanced~45 min

First Windows Form

form.vb
Public Class MainForm
    Inherits Form

    Private btn As New Button() With { _
        .Text = "Click Me", _
        .Location = New Point(50, 50) _
    }

    Public Sub New()
        Me.Text = "Hello VB"
        Me.Size = New Size(300, 200)
        AddHandler btn.Click, AddressOf Btn_Click
        Me.Controls.Add(btn)
    End Sub

    Private Sub Btn_Click(sender As Object, e As EventArgs)
        MessageBox.Show("Hello!")
    End Sub
End Class

Common Controls

ControlPurpose
TextBoxSingle-line text input
LabelStatic text
ButtonClickable button
ComboBoxDrop-down list
ListBoxList of items
DataGridViewTabular data display
Practice

Build a temperature converter form (Celsius โ†” Fahrenheit).

Lecture 15 ยท Desktop Apps

Events & Delegates

Intermediate~45 min

Custom Events

event.vb
Class Counter
    Public Event ThresholdReached(value As Integer)
    Private count As Integer = 0
    Sub Increment()
        count += 1
        If count = 10 Then
            RaiseEvent ThresholdReached(count)
        End If
    End Sub
End Class

Dim c As New Counter()
AddHandler c.ThresholdReached, Sub(v) Console.WriteLine($"Reached {v}!")
For i = 1 To 10 : c.Increment() : Next

Delegates

deleg.vb
Delegate Function MathOp(a As Integer, b As Integer) As Integer

Dim add As MathOp = Function(a, b) a + b
Dim mul As MathOp = Function(a, b) a * b
Console.WriteLine(add(2, 3))  ' 5
Console.WriteLine(mul(2, 3))  ' 6
Practice

Build a Stopwatch class that raises a Tick event every second.

Lecture 16 ยท Desktop Apps

ADO.NET Database

Advanced~45 min

SQL Connection

db.vb
Imports System.Data.SqlClient

Dim cs As String = "Server=.;Database=Shop;Integrated Security=True"
Using conn As New SqlConnection(cs)
    conn.Open()
    Dim cmd As New SqlCommand("SELECT * FROM Products", conn)
    Using reader = cmd.ExecuteReader()
        While reader.Read()
            Console.WriteLine(reader("Name"))
        End While
    End Using
End Using

Insert / Update

crud.vb
Dim cmd As New SqlCommand(
    "INSERT INTO Products (Name, Price) VALUES (@n, @p)", conn)
cmd.Parameters.AddWithValue("@n", "Apple")
cmd.Parameters.AddWithValue("@p", 1.5)
cmd.ExecuteNonQuery()

DataAdapter & DataSet

adapter.vb
Dim adapter As New SqlDataAdapter("SELECT * FROM Products", conn)
Dim ds As New DataSet()
adapter.Fill(ds, "Products")
dataGridView1.DataSource = ds.Tables("Products")
Practice

Build a contact manager that stores names and phones in SQL Server.

Lecture 17 ยท Desktop Apps

Async & Threading

Advanced~45 min

Async / Await

async.vb
Async Function FetchAsync(url As String) As Task(Of String)
    Using client As New HttpClient()
        Return Await client.GetStringAsync(url)
    End Using
End Function

Private Async Sub btnLoad_Click(sender As Object, e As EventArgs)
    Dim html = Await FetchAsync("https://example.com")
    txtResult.Text = html
End Sub

Threading

thread.vb
Imports System.Threading

Dim t As New Thread(Sub()
    For i = 1 To 5
        Console.WriteLine($"Worker: {i}")
        Thread.Sleep(500)
    Next
End Sub)
t.Start()

BackgroundWorker

bgw.vb
AddHandler bgWorker.DoWork, Sub(s, e) e.Result = LongTask()
AddHandler bgWorker.RunWorkerCompleted, Sub(s, e) lbl.Text = e.Result.ToString()
bgWorker.RunWorkerAsync()
Practice

Build an async file downloader with progress bar.

Lecture 18 ยท Capstone

Capstone: Inventory Manager Desktop App

Advanced~60 min

Project Overview

Build a full inventory management Windows Forms application using everything you've learned.

Features

  • User login screen (with hashed passwords)
  • Product CRUD via SQL Server
  • Stock-low alerts
  • Invoice generation & PDF export
  • Sales reports with charts
  • Multi-user roles (admin / cashier)

Architecture

structure.txt
InventoryApp/
  Forms/        ' Windows Forms .vb files
    LoginForm.vb
    MainForm.vb
    ProductForm.vb
  Models/       ' Domain classes
    Product.vb
    User.vb
  Data/         ' ADO.NET data access
    ProductRepository.vb
  Helpers/      ' PDF, hashing utilities
  Program.vb    ' Entry point

Bonus Challenges

  • Add barcode scanner integration
  • Export reports to Excel using EPPlus
  • Add a dashboard with charts (System.Windows.Forms.DataVisualization)
  • Package as MSI installer
Final Challenge

Build the full app. Deploy it as an MSI installer. Share GitHub link!