Creating a Module
✅ What is a Module?
- A Module in VB.NET is a container for procedures, functions, variables, and declarations.
- It is similar to a class but cannot be instantiated (no objects).
- Members inside a module are shared by default, accessible without creating an instance.
- Used to organize related procedures and variables for reuse throughout the program.
🧩 Key Features of a Module
- Declared using the keyword
Module. - All members are implicitly
Shared(static). - Cannot be inherited or instantiated.
- Useful for utility functions, global variables, constants.
📝 Syntax of a Module
Module ModuleName
' Variable declaration
Public globalVariable As Integer = 100
' Procedure
Sub DisplayMessage()
Console.WriteLine("Hello from Module!")
End Sub
' Function
Function AddNumbers(ByVal a As Integer, ByVal b As Integer) As Integer
Return a + b
End Function
End Module
✅ How to Create a Module
- Define the module with the
Modulekeyword followed by the module name. - Add procedures, functions, variables, or constants inside the module.
- Call module members directly by their names anywhere in the same project or with the module name prefix.
🧑💻 Example of Creating and Using a Module
Module MathOperations
' Function to add two numbers
Function Add(a As Integer, b As Integer) As Integer
Return a + b
End Function
' Procedure to display result
Sub ShowResult(result As Integer)
Console.WriteLine("Result is: " & result)
End Sub
End Module
Module Program
Sub Main()
Dim sum As Integer = MathOperations.Add(10, 20)
MathOperations.ShowResult(sum)
End Sub
End Module
Output:
Result is: 30
✅ Advantages of Using Modules
- Code reusability: Group related functions/procedures in one place.
- Simplifies access to shared data and methods without creating objects.
- Helps to organize code logically.
- Useful for defining global variables and constants accessible across the application.
⚠ Important Notes
- Modules provide global scope but use them carefully to avoid excessive use of global variables.
- For object-oriented design, prefer using Classes over Modules.
- Members of modules are
Sharedby default; you cannot declare instance members.
📝 Summary Table
| Term | Description |
|---|---|
| Module | Container for shared procedures, functions, and variables |
| Declared with | Module keyword |
| Instantiation | Not possible (no objects) |
| Member scope | Shared (global) by default |
| Usage | Organizing utility code and global data |
Sub Procedures
✅ What is a Sub Procedure?
- A Sub procedure is a block of code that performs a specific task but does not return a value.
- It is used to organize and reuse code for performing actions.
- Declared using the keyword
Sub. - Can accept parameters and can be called from anywhere in the program.
📝 Syntax of a Sub Procedure
Sub ProcedureName([parameters])
' Code statements
End Sub
ProcedureNameis the name of the Sub procedure.- Parameters are optional and are used to pass data into the procedure.
✅ Key Features of Sub Procedures
- Does not return any value (unlike functions).
- Can have parameters (ByVal or ByRef) for input/output.
- Can be called by writing its name and passing arguments if required.
- Improves code modularity and readability.
🧑💻 Example of a Simple Sub Procedure
Sub DisplayMessage()
Console.WriteLine("Hello, welcome to VB.NET!")
End Sub
' Calling the Sub
DisplayMessage()
Output:
Hello, welcome to VB.NET!
✅ Sub Procedures with Parameters
- Parameters allow passing information to the Sub.
- Parameters can be passed by value (ByVal) or by reference (ByRef).
Sub GreetUser(ByVal userName As String)
Console.WriteLine("Hello, " & userName & "!")
End Sub
' Calling the Sub with argument
GreetUser("Praveen")
Output:
Hello, Praveen!
Difference between ByVal and ByRef Parameters
| Parameter Type | Description |
|---|---|
| ByVal | Passes a copy of the argument; changes inside Sub do not affect original variable. |
| ByRef | Passes reference to the original variable; changes inside Sub affect original variable. |
Example of ByRef:
Sub Increment(ByRef number As Integer)
number += 1
End Sub
Dim x As Integer = 5
Increment(x)
Console.WriteLine(x) ' Output: 6
✅ Calling a Sub Procedure
- Simply use the Sub name and pass any required arguments.
- Parentheses are optional if there are no arguments.
Sub DisplayInfo()
Console.WriteLine("This is a Sub procedure.")
End Sub
' Call without parentheses
DisplayInfo()
' Call with parentheses
DisplayInfo()
✅ Advantages of Using Sub Procedures
- Promotes code reuse.
- Makes code more organized and readable.
- Helps divide complex programs into smaller manageable parts.
- Facilitates better maintenance and debugging.
⚠ Important Points
- Sub procedures cannot return a value. Use Functions if a return value is needed.
- Sub procedures can be declared inside modules, classes, or structures.
- Use meaningful names for Subs to improve code clarity.
📝 Summary Table
| Term | Description |
|---|---|
| Sub Procedure | Code block performing tasks, no return value |
| Declared with | Sub keyword |
| Parameters | Optional, can be ByVal or ByRef |
| Return value | None |
| Usage | Organize code, perform specific actions |
Arrays
✅ What is an Array?
- An array is a collection of variables of the same data type stored in contiguous memory locations.
- It allows you to store multiple values under a single variable name.
- Each element in an array is identified by an index.
- Arrays are useful when you need to work with a fixed number of related items.
🧩 Key Features of Arrays
- Fixed size (length is defined at the time of creation).
- Elements are accessed using zero-based indexing (first element is at index 0).
- Can be single-dimensional or multi-dimensional.
- All elements must be of the same data type.
📝 Declaring Arrays in VB.NET
Dim arrayName(size) As DataType
sizeis the number of elements minus one (because indexing starts at 0).
Example:
Dim numbers(4) As Integer ' Declares an integer array with 5 elements (0 to 4)
✅ Initializing Arrays
- At the time of declaration
Dim fruits() As String = {"Apple", "Banana", "Cherry"}
- Later initialization
Dim numbers(2) As Integer
numbers(0) = 10
numbers(1) = 20
numbers(2) = 30
✅ Accessing Array Elements
- Use the index to get or set values.
Console.WriteLine(fruits(1)) ' Outputs: Banana
numbers(2) = 50 ' Update the third element to 50
🧑💻 Example: Using a Single-Dimensional Array
Module Program
Sub Main()
Dim scores() As Integer = {90, 85, 78, 92, 88}
For i As Integer = 0 To scores.Length - 1
Console.WriteLine("Score at index " & i & ": " & scores(i))
Next
End Sub
End Module
✅ Multi-Dimensional Arrays
- Arrays can have more than one dimension like 2D, 3D arrays, etc.
- Commonly used to represent tables or matrices.
Syntax for 2D array:
Dim matrix(2, 3) As Integer ' 3 rows and 4 columns (indices 0 to 2, and 0 to 3)
Example:
Dim matrix(,) As Integer = {{1, 2, 3}, {4, 5, 6}}
Console.WriteLine(matrix(1, 2)) ' Outputs: 6
✅ Important Array Properties and Methods
| Property/Method | Description |
|---|---|
Length |
Returns the total number of elements |
GetLength(d) |
Returns the number of elements in dimension d (0-based) |
Rank |
Returns the number of dimensions |
⚠ Important Points
- Arrays have fixed size once declared; you cannot resize them. To handle dynamic collections, use Collections like
List(Of T). - Indexing starts at 0.
- Accessing an invalid index causes a runtime error (
IndexOutOfRangeException). - Use loops (For, For Each) to iterate through array elements.
📝 Summary Table
| Concept | Description | Example |
|---|---|---|
| Array Declaration | Declaring fixed size array | Dim nums(4) As Integer |
| Array Initialization | Assigning values at declaration or later | Dim fruits() As String = {"A", "B"} |
| Access Elements | Using index to get/set values | fruits(0) = "Apple" |
| Multi-Dimensional | Array with more than one dimension | Dim matrix(1,2) As Integer |
| Properties | Length, Rank, GetLength(d) |
array.Length |
Collections
✅ What are Collections?
- Collections are dynamic data structures that can store groups of related objects.
- Unlike arrays, collections can grow or shrink dynamically as needed.
- They provide more flexibility and functionality than arrays.
- Collections are part of the System.Collections or System.Collections.Generic namespaces.
🧩 Types of Collections
-
Non-Generic Collections (older, less type-safe)
-
Examples:
ArrayList,Hashtable,Queue,Stack -
Generic Collections (preferred, type-safe)
-
Examples:
List(Of T),Dictionary(Of TKey, TValue),Queue(Of T),Stack(Of T)
✅ Advantages of Collections over Arrays
| Collections | Arrays |
|---|---|
| Dynamic size (can grow/shrink) | Fixed size (declared size cannot change) |
| Can store objects of different types (non-generic) | Store same data type only |
| Rich set of methods for adding, removing, searching, sorting | Limited built-in methods |
| Type-safe (generic collections) | Type-safe by definition |
🧑💻 Examples of Common Collections in VB.NET
1. ArrayList (Non-Generic)
- Stores objects dynamically, but not type-safe.
- Can hold any type of object.
Dim arrList As New ArrayList()
arrList.Add(10)
arrList.Add("Hello")
arrList.Add(3.14)
For Each item In arrList
Console.WriteLine(item)
Next
2. List(Of T) (Generic Collection)
- Stores items of a specific type.
- Provides methods like
Add,Remove,Contains,Count.
Dim intList As New List(Of Integer)()
intList.Add(5)
intList.Add(10)
intList.Add(15)
For Each num As Integer In intList
Console.WriteLine(num)
Next
3. Dictionary(Of TKey, TValue)
- Stores key-value pairs.
- Keys are unique.
- Used for fast lookups by key.
Dim dict As New Dictionary(Of String, String)()
dict.Add("US", "United States")
dict.Add("IN", "India")
Console.WriteLine(dict("IN")) ' Output: India
✅ Common Methods of Collections
| Method | Description |
|---|---|
Add |
Adds an item to the collection |
Remove |
Removes a specific item |
RemoveAt |
Removes item at a specific index |
Contains |
Checks if an item exists |
Clear |
Removes all items |
Count |
Gets the number of elements |
Item or [] |
Access item by index or key |
✅ When to Use Collections
- When the number of elements is not fixed or changes dynamically.
- When you need advanced functionalities like searching, sorting, or key-value mapping.
- When you want type safety using generic collections.
- When you want to work with heterogeneous objects (use non-generic collections).
⚠ Important Notes
- Prefer generic collections (
List(Of T),Dictionary(Of TKey, TValue)) over non-generic for type safety and performance. - Collections are reference types, so large collections consume memory.
- Always handle exceptions like KeyNotFoundException when working with dictionaries.
📝 Summary Table
| Collection Type | Description | Namespace | Example Use Case |
|---|---|---|---|
ArrayList |
Dynamic, non-generic list | System.Collections |
Mixed data types |
List(Of T) |
Generic dynamic list | System.Collections.Generic |
Type-safe, homogeneous lists |
Dictionary(Of TKey, TValue) |
Key-value pairs, fast lookups | System.Collections.Generic |
Lookup tables by key |
Queue(Of T) |
FIFO collection | System.Collections.Generic |
Order processing, buffers |
Stack(Of T) |
LIFO collection | System.Collections.Generic |
Undo functionality, reverse order |
System.Collections Namespace
✅ What is System.Collections Namespace?
- The System.Collections namespace provides non-generic collection classes to store and manage groups of objects.
- It includes a variety of data structures like lists, queues, stacks, hash tables, etc.
- These collections store objects as type
Object, meaning they can hold any type, but lack type safety. - Introduced in early versions of .NET before generic collections were added.
🧩 Key Classes in System.Collections
| Class | Description |
|---|---|
ArrayList |
Dynamic array that can grow/shrink dynamically, stores objects of any type |
Hashtable |
Stores key-value pairs; keys and values are objects; uses hashing for fast lookup |
Queue |
Represents a First-In-First-Out (FIFO) collection |
Stack |
Represents a Last-In-First-Out (LIFO) collection |
SortedList |
Stores key-value pairs sorted by key |
BitArray |
Manages a compact array of bits (true/false values) |
✅ Common Characteristics of System.Collections Classes
- Store data as objects (
Objecttype), so boxing/unboxing may occur for value types. - Do not provide compile-time type safety (runtime errors possible if wrong type used).
- Provide useful methods for adding, removing, searching, and enumerating elements.
- Useful when working with legacy code or when you need to store heterogeneous objects.
🧑💻 Examples of System.Collections Classes
1. ArrayList Example
Dim arrList As New ArrayList()
arrList.Add(10)
arrList.Add("VB.NET")
arrList.Add(DateTime.Now)
For Each item In arrList
Console.WriteLine(item)
Next
2. Hashtable Example
Dim hashtable As New Hashtable()
hashtable.Add("Name", "Praveen")
hashtable.Add("Age", 30)
Console.WriteLine("Name: " & hashtable("Name"))
Console.WriteLine("Age: " & hashtable("Age"))
3. Queue Example
Dim queue As New Queue()
queue.Enqueue("First")
queue.Enqueue("Second")
Console.WriteLine(queue.Dequeue()) ' Output: First
4. Stack Example
Dim stack As New Stack()
stack.Push("Bottom")
stack.Push("Top")
Console.WriteLine(stack.Pop()) ' Output: Top
✅ Advantages of System.Collections
- Simple and easy to use.
- Supports heterogeneous data storage.
- Useful for legacy applications.
⚠ Limitations of System.Collections
- Lack of type safety can cause runtime errors.
- Performance overhead due to boxing/unboxing of value types.
- Generic collections (
System.Collections.Generic) are preferred for new applications.
📝 Summary Table
| Class | Description | Behavior |
|---|---|---|
| ArrayList | Dynamic array | Resizable, holds any object |
| Hashtable | Key-value pairs | Fast lookup via hashing |
| Queue | FIFO collection | Enqueue and Dequeue items |
| Stack | LIFO collection | Push and Pop items |
| SortedList | Sorted key-value pairs | Sorted by key |
| BitArray | Array of bits (true/false) | Compact bit storage |