Variables and Identifiers
✅ What is a Variable?
A variable is a named storage location in the computer’s memory that holds data which can be changed during program execution.
- Think of variables as containers for storing values.
-
Each variable has:
-
A name (identifier)
- A data type (e.g., Integer, String)
- A value that can be assigned or modified.
🧩 Example of Variable Declaration in VB.NET:
Dim age As Integer
Dim name As String
- Here,
ageandnameare variables. IntegerandStringare their data types.
✅ Characteristics of Variables
| Characteristic | Explanation |
|---|---|
| Name | Variables have unique names called identifiers. |
| Data Type | Defines what kind of data the variable can store. |
| Memory Location | The computer allocates memory space to store the variable’s value. |
| Value | Variables can hold different values during program execution. |
✅ What is an Identifier?
An identifier is the name given to a variable, function, procedure, class, or any other user-defined item in the program.
📝 Rules for Naming Identifiers in VB.NET:
- Must begin with a letter (A-Z, a-z).
- Can contain letters, digits (0-9), and underscore (_) characters.
- Cannot contain spaces or special characters like
@, #, $, %, &, *. - Cannot be a reserved keyword (e.g.,
Dim,If,For). - Identifiers are case-insensitive (
Ageandageare same). - Should be meaningful and descriptive to improve code readability.
- Maximum length is 255 characters.
✅ Examples of Valid and Invalid Identifiers
| Valid Identifiers | Invalid Identifiers |
|---|---|
studentName |
2ndStudent (starts with digit) |
_totalCount |
first name (contains space) |
Age_2023 |
If (reserved keyword) |
counter |
@price (special character) |
🧑💻 Declaring and Initializing Variables
- Declaration: Creating the variable with a type.
- Initialization: Assigning a value to the variable.
Dim score As Integer ' Declaration
score = 100 ' Initialization
Dim message As String = "Hello World" ' Declaration + Initialization
✅ Types of Variables (Based on Scope)
| Type | Description |
|---|---|
| Local Variables | Declared inside a procedure or method; accessible only within it. |
| Global Variables | Declared outside all procedures; accessible throughout the program. |
| Static Variables | Retain their value between procedure calls. |
📝 Summary:
- Variables store data and have unique names called identifiers.
- Identifiers must follow rules: start with a letter, no spaces/special chars, not keywords.
- Variables have data types that define what kind of data they hold.
- Variables can be declared and initialized to hold values.
- Proper naming improves program clarity and maintainability.
Data Types and Keywords
✅ What Are Data Types?
A data type defines the type of data a variable can hold and the amount of memory allocated for it.
- It also determines what operations can be performed on the data.
- In .NET (VB.NET), data types are strongly typed, meaning each variable must have a declared type.
🧩 Common Data Types in VB.NET
| Data Type | Description | Memory Size | Example Values |
|---|---|---|---|
Integer |
Whole numbers | 4 bytes | 0, 100, -50 |
Long |
Large whole numbers | 8 bytes | 1234567890 |
Short |
Small whole numbers | 2 bytes | -32768 to 32767 |
Byte |
Unsigned small numbers (0-255) | 1 byte | 0 to 255 |
Double |
Floating-point numbers (decimal) | 8 bytes | 3.1415, -0.002 |
Single |
Floating-point numbers (decimal, less precision) | 4 bytes | 2.5, 0.33 |
Decimal |
High precision decimal numbers | 16 bytes | 1000.25, 3.1415926535 |
Boolean |
True or False | 2 bytes | True, False |
Char |
Single Unicode character | 2 bytes | "A", "z", "1" |
String |
Sequence of characters (text) | Variable | "Hello", "Dotnet" |
Date |
Date and time | 8 bytes | 2025-06-09, 12:00 PM |
🧑💻 Example of Declaring Variables with Data Types:
Dim age As Integer = 25
Dim price As Decimal = 99.99D
Dim isAvailable As Boolean = True
Dim firstLetter As Char = "A"c
Dim name As String = "Praveen"
Dim currentDate As Date = #6/9/2025#
✅ Why Data Types Are Important?
- Enforce data integrity by restricting values.
- Optimize memory usage.
- Help the compiler check errors before runtime.
- Enable appropriate operations on data (e.g., math on numbers, concatenation on strings).
🔑 Keywords in VB.NET
Keywords are reserved words that have special meaning in the language syntax. They cannot be used as identifiers (variable names, function names, etc.).
📝 Common VB.NET Keywords
| Keyword | Purpose/Meaning |
|---|---|
Dim |
Declares a variable |
Sub |
Declares a procedure (void method) |
Function |
Declares a function (returns value) |
If |
Conditional statement |
Else |
Alternative conditional branch |
For |
Loop statement |
While |
Loop statement |
Select |
Used in Select Case statements |
Case |
Defines case in Select Case |
True |
Boolean literal |
False |
Boolean literal |
Nothing |
Represents a null reference |
Exit |
Exits a loop or procedure |
Try |
Begins exception handling block |
Catch |
Exception handling block |
Class |
Defines a class |
Module |
Defines a module |
Public |
Access modifier |
Private |
Access modifier |
Imports |
Imports namespaces or libraries |
📝 How to Handle Keywords in Identifiers?
- If you must use a keyword as an identifier, enclose it in square brackets
[ ].
Example:
Dim [If] As Integer = 10
But this is generally discouraged to avoid confusion.
📝 Summary
- Data Types define the kind of data a variable can hold and determine memory allocation.
- VB.NET has a rich set of built-in data types for numbers, text, dates, and logical values.
- Keywords are reserved words that form the language syntax and cannot be used as names.
- Knowing keywords is essential to understand and write valid VB.NET programs.
Operators
✅ What Are Operators?
Operators are special symbols or keywords that perform operations on one or more operands (variables or values) to produce a result.
🧩 Types of Operators in VB.NET
| Operator Type | Description | Examples |
|---|---|---|
| Arithmetic Operators | Perform mathematical calculations | +, -, *, /, \, Mod |
| Relational (Comparison) Operators | Compare two values and return Boolean result | =, <>, <, >, <=, >= |
| Logical Operators | Perform logical operations on Boolean values | And, Or, Not, AndAlso, OrElse |
| Assignment Operator | Assigns values to variables | = |
| Concatenation Operator | Combines strings | & |
| Other Operators | Includes Is, Like, TypeOf, etc. |
Is, Like, TypeOf |
1️⃣ Arithmetic Operators
Used to perform basic mathematical operations.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 10 - 4 |
6 |
* |
Multiplication | 7 * 2 |
14 |
/ |
Division (floating-point) | 10 / 4 |
2.5 |
\ |
Integer division | 10 \ 4 |
2 |
Mod |
Modulus (remainder) | 10 Mod 4 |
2 |
2️⃣ Relational Operators
Compare two values and return a Boolean (True or False).
| Operator | Meaning | Example | Result |
|---|---|---|---|
= |
Equal to | 5 = 5 |
True |
<> |
Not equal to | 5 <> 3 |
True |
< |
Less than | 4 < 6 |
True |
> |
Greater than | 8 > 10 |
False |
<= |
Less than or equal | 5 <= 5 |
True |
>= |
Greater than or equal | 7 >= 3 |
True |
3️⃣ Logical Operators
Used to combine or invert Boolean expressions.
| Operator | Meaning | Example | Result |
|---|---|---|---|
And |
Logical AND (both True) | True And False |
False |
Or |
Logical OR (any True) | True Or False |
True |
Not |
Logical NOT (negation) | Not True |
False |
AndAlso |
Short-circuit AND | Only evaluates second if first is True | Similar to And but efficient |
OrElse |
Short-circuit OR | Only evaluates second if first is False | Similar to Or but efficient |
4️⃣ Assignment Operator
=assigns a value to a variable.
Example:
Dim a As Integer
a = 10 ' Assigns value 10 to variable a
5️⃣ Concatenation Operator
&operator combines two strings.
Example:
Dim firstName As String = "John"
Dim lastName As String = "Doe"
Dim fullName As String = firstName & " " & lastName ' Result: "John Doe"
6️⃣ Other Operators
| Operator | Purpose | Example |
|---|---|---|
Is |
Checks if two object references are the same | If obj1 Is obj2 Then |
Like |
Used for pattern matching in strings | If name Like "J*" |
TypeOf |
Checks object type | If TypeOf obj Is Button Then |
📝 Operator Precedence
- Operators follow an order of precedence that determines the sequence of evaluation.
- Example precedence (highest to lowest):
| Precedence | Operators |
|---|---|
| 1 | (), method calls |
| 2 | +, - (unary) |
| 3 | *, /, \, Mod |
| 4 | +, - (binary addition/subtraction) |
| 5 | Relational (=, <, >, etc.) |
| 6 | Logical NOT (Not) |
| 7 | Logical AND (And, AndAlso) |
| 8 | Logical OR (Or, OrElse) |
| 9 | Assignment (=) |
Use parentheses () to override precedence and clarify expressions.
🧑💻 Examples
Dim x As Integer = 10
Dim y As Integer = 20
Dim z As Integer
z = x + y * 2 ' Result: 10 + (20*2) = 50
z = (x + y) * 2 ' Result: (10+20)*2 = 60
Dim isAdult As Boolean = (age >= 18) And (age <= 60)
Dim fullName As String = firstName & " " & lastName
📝 Summary
- Operators perform operations on variables and values.
- Arithmetic operators handle math operations.
- Relational operators compare values.
- Logical operators combine Boolean expressions.
&concatenates strings.- Use parentheses to control evaluation order.
Decision Structures
✅ What Are Decision Structures?
Decision structures (also called conditional statements) allow a program to choose different actions based on conditions. They help control the flow of execution by making decisions.
🧩 Types of Decision Structures in VB.NET
- If...Then Statement
- If...Then...Else Statement
- If...Then...ElseIf...Else Statement
- Select Case Statement
1️⃣ If...Then Statement
- Executes a block of code only if a specified condition is True.
Syntax:
If condition Then
' Statements to execute if condition is True
End If
Example:
If age >= 18 Then
Console.WriteLine("You are an adult.")
End If
2️⃣ If...Then...Else Statement
- Executes one block of code if the condition is True, otherwise executes an alternative block.
Syntax:
If condition Then
' Statements if True
Else
' Statements if False
End If
Example:
If age >= 18 Then
Console.WriteLine("You are an adult.")
Else
Console.WriteLine("You are a minor.")
End If
3️⃣ If...Then...ElseIf...Else Statement
- Allows multiple conditions to be tested in sequence.
Syntax:
If condition1 Then
' Statements if condition1 is True
ElseIf condition2 Then
' Statements if condition2 is True
Else
' Statements if all conditions are False
End If
Example:
If score >= 90 Then
Console.WriteLine("Grade: A")
ElseIf score >= 75 Then
Console.WriteLine("Grade: B")
ElseIf score >= 60 Then
Console.WriteLine("Grade: C")
Else
Console.WriteLine("Grade: F")
End If
4️⃣ Select Case Statement
- Provides an alternative to multiple If...ElseIf statements.
- Evaluates an expression once and executes the matching Case block.
Syntax:
Select Case expression
Case value1
' Statements for value1
Case value2
' Statements for value2
Case Else
' Statements if no Case matches
End Select
Example:
Select Case dayOfWeek
Case 1
Console.WriteLine("Sunday")
Case 2
Console.WriteLine("Monday")
Case 3
Console.WriteLine("Tuesday")
Case Else
Console.WriteLine("Invalid day")
End Select
✅ Important Points:
- Conditions in If and Select Case statements must evaluate to a Boolean value (
TrueorFalse). - You can nest decision structures inside each other for complex logic.
- Use Else or Case Else to handle unexpected or default cases.
- The Select Case is often preferred for cleaner syntax when checking one variable against many values.
🧑💻 Sample Code Combining Decision Structures
Dim age As Integer = 20
If age < 13 Then
Console.WriteLine("Child")
ElseIf age < 20 Then
Console.WriteLine("Teenager")
Else
Console.WriteLine("Adult")
End If
Dim choice As Integer = 2
Select Case choice
Case 1
Console.WriteLine("Option 1 selected")
Case 2
Console.WriteLine("Option 2 selected")
Case Else
Console.WriteLine("Invalid option")
End Select
📝 Summary:
- Decision structures control the program flow based on conditions.
If...Then,If...Then...Else, andIf...Then...ElseIfhandle conditional logic.Select Caseis useful for multiple discrete values.- Use Else/Case Else to handle default situations.
Looping Structures
✅ What Are Looping Structures?
Looping structures allow a set of statements to be repeated multiple times based on a condition or a counter. They help automate repetitive tasks and control the flow of execution.
🧩 Types of Loops in VB.NET
- For...Next Loop
- For Each...Next Loop
- While...End While Loop
- Do...Loop (Do While / Do Until)
1️⃣ For...Next Loop
- Executes a block of code a specific number of times.
- Uses a loop counter that increments or decrements each iteration.
Syntax:
For counter As Integer = start To end [Step step]
' Statements to repeat
Next
- Step is optional; default is 1.
- Loop runs from
starttoend.
Example:
For i As Integer = 1 To 5
Console.WriteLine("Iteration: " & i)
Next
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
2️⃣ For Each...Next Loop
- Iterates through each element in a collection or array.
- Useful for processing items without worrying about indexes.
Syntax:
For Each element As DataType In collection
' Statements to repeat for each element
Next
Example:
Dim fruits As String() = {"Apple", "Banana", "Cherry"}
For Each fruit As String In fruits
Console.WriteLine(fruit)
Next
Output:
Apple
Banana
Cherry
3️⃣ While...End While Loop
- Repeats a block of code while a condition is True.
- Condition is checked before each iteration.
Syntax:
While condition
' Statements to repeat
End While
Example:
Dim count As Integer = 1
While count <= 5
Console.WriteLine("Count: " & count)
count += 1
End While
4️⃣ Do...Loop
-
Executes a block of code repeatedly either:
-
Do While — condition checked at the beginning (pre-test loop)
- Do Until — loop continues until condition becomes True
- Do...Loop While — condition checked at the end (post-test loop)
- Do...Loop Until — condition checked at the end
Syntax:
Do While condition
' Statements to repeat
Loop
Do Until condition
' Statements to repeat
Loop
Do
' Statements
Loop While condition
Do
' Statements
Loop Until condition
Examples:
Dim i As Integer = 1
' Do While example
Do While i <= 5
Console.WriteLine(i)
i += 1
Loop
' Do Until example
i = 1
Do Until i > 5
Console.WriteLine(i)
i += 1
Loop
✅ Loop Control Statements
| Statement | Description |
|---|---|
Exit For |
Exits the current For loop immediately |
Exit While |
Exits the current While loop immediately |
Exit Do |
Exits the current Do loop immediately |
Continue For |
Skips current iteration, proceeds to next in For loop |
Continue While |
Skips current iteration, proceeds to next in While loop |
📝 Summary
| Loop Type | When to Use | Condition Check |
|---|---|---|
For...Next |
When you know the exact number of iterations | Before each iteration |
For Each...Next |
When iterating through elements in a collection | Before each iteration |
While...End While |
When condition needs to be checked before loop starts | Before each iteration |
Do...Loop |
When condition can be checked before or after loop | Before or after |
🧑💻 Example of Combined Loops
' For Loop Example
For i As Integer = 1 To 3
Console.WriteLine("For Loop: " & i)
Next
' For Each Loop Example
Dim names As String() = {"Alice", "Bob", "Charlie"}
For Each name As String In names
Console.WriteLine("For Each Loop: " & name)
Next
' While Loop Example
Dim count As Integer = 1
While count <= 3
Console.WriteLine("While Loop: " & count)
count += 1
End While
' Do Loop Example
Dim num As Integer = 1
Do
Console.WriteLine("Do Loop: " & num)
num += 1
Loop While num <= 3
Timer Controls
✅ What is a Timer Control?
- A Timer control is a component in .NET used to generate recurring events at specified intervals.
- It allows a program to execute code repeatedly or after a set delay without user interaction.
- Timer runs in the background and raises a Tick event at every interval.
🔑 Key Properties of Timer Control
| Property | Description |
|---|---|
| Interval | Time interval in milliseconds between Tick events. |
| Enabled | Starts or stops the timer (True = running, False = stopped). |
| AutoReset | (In some timer types) Whether the timer restarts automatically after elapsed. |
🕹 Types of Timer Controls in .NET
-
Windows Forms Timer (
System.Windows.Forms.Timer) -
Used in Windows Forms applications.
- Runs on the UI thread, suitable for updating UI elements.
-
Not very precise, depends on message processing.
-
System.Timers.Timer
-
More precise, runs on a separate thread.
- Suitable for server-side or background tasks.
-
Supports AutoReset property.
-
System.Threading.Timer
-
Executes on ThreadPool threads.
- Lightweight and for high-performance tasks.
🛠 Using Timer Control in Windows Forms
- Add Timer control to the form (drag from Toolbox or instantiate in code).
- Set the Interval property (e.g., 1000 for 1 second).
- Handle the Tick event to specify what happens on each tick.
- Start the timer by setting Enabled = True or calling
timer.Start(). - Stop the timer by setting Enabled = False or calling
timer.Stop().
🔄 Example of Timer in Windows Forms (VB.NET)
' Create a Timer object
Dim WithEvents myTimer As New System.Windows.Forms.Timer()
Sub SetupTimer()
myTimer.Interval = 1000 ' 1000 ms = 1 second
myTimer.Enabled = True ' Start the timer
End Sub
' Tick event handler
Private Sub myTimer_Tick(sender As Object, e As EventArgs) Handles myTimer.Tick
' Code to run every second
Console.WriteLine("Timer Tick at " & DateTime.Now.ToLongTimeString())
End Sub
✅ Common Uses of Timer Control
- Creating clocks or countdown timers.
- Updating UI elements at regular intervals.
- Polling or checking status periodically.
- Animations or slideshows.
- Scheduled repetitive tasks.
⚠ Important Notes
- For UI updates, use
System.Windows.Forms.Timerbecause it works on the UI thread. - Avoid long processing inside Tick event to prevent UI freezing.
- For background or server tasks, use
System.Timers.TimerorSystem.Threading.Timer. - Always stop and dispose timers when no longer needed to free resources.
📝 Summary
| Feature | Description |
|---|---|
| Timer control | Generates recurring events at intervals |
| Interval | Time between events in milliseconds |
| Tick event | Raised on each timer interval |
| Types | Windows Forms Timer, System.Timers.Timer, System.Threading.Timer |
| Usage | UI updates, background processing, scheduled tasks |