InterviewPitch
VisualBasic interview questions

VisualBasic Interview Questions with Answers

Most Asked VisualBasic Interview Questions for Software Engineer Roles

100+ QuestionsDetailed AnswersCode ExamplesUpdated for 2026

Introduction

This page provides a complete collection of Visual Basic Interview Questions and Answers designed for VB developers, .NET developers, software engineers, and candidates preparing for programming interviews. Visual Basic (VB) is a programming language developed by Microsoft that enables developers to build Windows applications, desktop software, database applications, and enterprise solutions. It is widely used with the .NET framework for rapid application development. This interview guide covers beginner, intermediate, and advanced Visual Basic concepts including VB syntax, variables, data types, control statements, object-oriented programming, classes, inheritance, exception handling, Windows Forms, ADO.NET, LINQ, and real-world development scenarios.

Why Visual Basic?

  • Rapid Application Development (RAD) – quick prototyping and development
  • Seamless .NET integration – full access to the .NET framework libraries
  • Windows-native – ideal for building desktop and enterprise Windows applications
  • Rich IDE support – Visual Studio provides excellent tooling and debugging
  • Strong database connectivity – ADO.NET and Entity Framework for data access
  • Large ecosystem and community – extensive resources and third-party libraries
  • Widely used in enterprise environments – many legacy and modern systems rely on VB

Most Asked Visual Basic Interview Questions

Beginner
1. What is Visual Basic?

Visual Basic (VB) is an event-driven, object-oriented programming language from Microsoft. It's designed for building Windows applications and is part of the .NET framework.

  • Event-driven: Responds to user events
  • Object-oriented: Supports classes, inheritance, polymorphism
  • .NET framework: Part of the .NET ecosystem
  • Rapid application development: Drag-and-drop UI design
  • Easy to learn: Simple syntax for beginners
vb
' Hello World in Visual Basic
Module Module1
    Sub Main()
        Console.WriteLine("Hello, World!")
    End Sub
End Module

' Using function
Module HelloWorld
    Function Greet() As String
        Return "Hello, World!"
    End Function
    
    Sub Main()
        Console.WriteLine(Greet())
    End Sub
End Module
Beginner
2. How to declare variables in Visual Basic?

Variables in Visual Basic are declared using Dim (mutable), ReadOnly (immutable), and Const (constants).

  • Dim: Mutable variable
  • ReadOnly: Immutable variable
  • Const: Compile-time constant
  • Type inference: Dim name = "Alice"
  • Explicit types: Dim name As String = "Alice"
vb
' Variables in Visual Basic
Module Variables
    Sub Main()
        ' Immutable variable (ReadOnly)
        ReadOnly immutableVar As String = "World"
        
        ' Mutable variable
        Dim mutableVar As String = "Hello"
        mutableVar = "Visual Basic"
        
        ' Type inference
        Dim inferred = 42
        
        ' Explicit type
        Dim explicit As Integer = 10
        
        ' Constants
        Const PI As Double = 3.14159
        
        ' Display
        Console.WriteLine(immutableVar)
        Console.WriteLine(mutableVar)
        Console.WriteLine(inferred)
        Console.WriteLine(explicit)
        Console.WriteLine(PI)
        
        ' Multiple declarations
        Dim a As Integer = 1, b As Integer = 2
    End Sub
End Module
Beginner
3. What are the data types in Visual Basic?

Visual Basic provides primitive types, value types, reference types, and generic collections.

  • Primitive: Integer, Long, Single, Double, Boolean, Char, String
  • Array: Integer()
  • List: List(Of T)
  • Dictionary: Dictionary(Of TKey, TValue)
  • Nullable: Integer?
  • Object: Object
vb
' Data Types in Visual Basic
Module DataTypes
    Sub Main()
        ' Integer types
        Dim intNum As Integer = 10
        Dim unsigned As UInteger = 100
        Dim smallInt As Short = 32767
        Dim largeInt As Long = 1000000
        
        ' Floating point
        Dim floatNum As Single = 3.14
        Dim doubleNum As Double = 3.14159
        
        ' Boolean
        Dim isActive As Boolean = True
        Dim isInactive As Boolean = False
        
        ' Character
        Dim charVal As Char = "A"c
        
        ' String
        Dim strVal As String = "Hello Visual Basic"
        
        ' Array
        Dim arr As Integer() = {1, 2, 3, 4, 5}
        
        ' List
        Dim list As New List(Of Integer) From {1, 2, 3, 4, 5}
        
        ' Dictionary
        Dim dict As New Dictionary(Of String, Integer)
        dict.Add("one", 1)
        dict.Add("two", 2)
        
        ' Object (nullable)
        Dim optional As Object = Nothing
        
        ' Type checking
        Console.WriteLine(intNum.GetType().Name)
    End Sub
End Module
Beginner
4. How to define functions in Visual Basic?

Functions in Visual Basic use the Function keyword, with support for optional parameters and multiple return values.

  • Function: Function name(params) As ReturnType
  • Sub: Sub name(params) (no return)
  • Optional params: Optional name As String = "Guest"
  • Multiple returns: Tuple return
  • Lambda: Function(x) x * 2
vb
' Functions in Visual Basic
Module Functions
    ' Basic function
    Function Add(a As Integer, b As Integer) As Integer
        Return a + b
    End Function
    
    ' Function with multiple return values (tuple)
    Function Divide(a As Integer, b As Integer) As (Integer, Integer)
        Return (a  b, a Mod b)
    End Function
    
    ' Function with optional parameters
    Function Greet(Optional name As String = "Guest") As String
        Return "Hello, " & name & "!"
    End Function
    
    ' Function with default parameters
    Function Multiply(a As Integer, Optional b As Integer = 2) As Integer
        Return a * b
    End Function
    
    ' Higher-order function
    Function Operate(a As Integer, b As Integer, op As Func(Of Integer, Integer, Integer)) As Integer
        Return op(a, b)
    End Function
    
    ' Lambda expression
    Dim multiply As Func(Of Integer, Integer, Integer) = Function(x, y) x * y
    
    Sub Main()
        Console.WriteLine(Add(5, 3))
        Dim result = Divide(10, 3)
        Console.WriteLine("Quotient: " & result.Item1 & ", Remainder: " & result.Item2)
        Console.WriteLine(Greet("Alice"))
        Console.WriteLine(Multiply(5))
        Console.WriteLine(Operate(6, 7, Function(x, y) x * y))
        Console.WriteLine(multiply(5, 3))
    End Sub
End Module
Coding Round
31. Reverse a string

Reverse a string using Array.Reverse or manual iteration.

  • Array.Reverse: Array.Reverse(chars)
  • Manual: Iterate from end to start
  • Return type: String
  • Complexity: O(n) time
vb
' Reverse a string in Visual Basic
Function ReverseString(str As String) As String
    Dim chars As Char() = str.ToCharArray()
    Array.Reverse(chars)
    Return New String(chars)
End Function

Function ReverseStringManual(str As String) As String
    Dim result As String = ""
    For i As Integer = str.Length - 1 To 0 Step -1
        result += str(i)
    Next
    Return result
End Function

Sub Main()
    Console.WriteLine(ReverseString("hello")) ' "olleh"
    Console.WriteLine(ReverseStringManual("hello")) ' "olleh"
End Sub
Coding Round
32. Check palindrome

Check if a string is a palindrome using Array.Reverse or two-pointer approach.

  • Array.Reverse: cleaned = reversed
  • Two-pointer: Compare from both ends
  • Case insensitive: ToLower()
  • Return type: Boolean
vb
' Check palindrome in Visual Basic
Function IsPalindrome(str As String) As Boolean
    Dim cleaned As String = str.ToLower().Replace(" ", "").Replace(".", "").Replace(",", "")
    Dim reversed As String = ReverseString(cleaned)
    Return cleaned = reversed
End Function

Function IsPalindromeTwoPointer(str As String) As Boolean
    Dim cleaned As String = str.ToLower().Replace(" ", "").Replace(".", "").Replace(",", "")
    Dim left As Integer = 0
    Dim right As Integer = cleaned.Length - 1
    While left < right
        If cleaned(left) <> cleaned(right) Then
            Return False
        End If
        left += 1
        right -= 1
    End While
    Return True
End Function

Sub Main()
    Console.WriteLine(IsPalindrome("racecar")) ' True
    Console.WriteLine(IsPalindrome("hello"))   ' False
    Console.WriteLine(IsPalindromeTwoPointer("A man a plan a canal Panama")) ' True
End Sub
Coding Round
33. Find max in array

Find maximum value using manual iteration or LINQ.

  • Manual: Iterate and track max
  • LINQ: arr.Max()
  • Empty array: Return Nothing
  • Return type: Integer?
vb
' Find max in array in Visual Basic
Function FindMax(arr As Integer()) As Integer?
    If arr.Length = 0 Then
        Return Nothing
    End If
    Dim max As Integer = arr(0)
    For Each num As Integer In arr
        If num > max Then
            max = num
        End If
    Next
    Return max
End Function

Sub Main()
    Dim numbers As Integer() = {1, 5, 3, 9, 2}
    Dim max As Integer? = FindMax(numbers)
    Console.WriteLine(max) ' 9
End Sub
Coding Round
34. Remove duplicates

Remove duplicates using HashSet(Of T) or LINQ.

  • HashSet: New HashSet(Of Integer)(arr)
  • LINQ: arr.Distinct().ToArray()
  • Return type: Integer()
  • Complexity: O(n) time
vb
' Remove duplicates in Visual Basic
Function RemoveDuplicates(arr As Integer()) As Integer()
    Dim seen As New HashSet(Of Integer)()
    Dim result As New List(Of Integer)()
    For Each item As Integer In arr
        If Not seen.Contains(item) Then
            seen.Add(item)
            result.Add(item)
        End If
    Next
    Return result.ToArray()
End Function

Sub Main()
    Dim numbers As Integer() = {1, 2, 2, 3, 3, 4}
    Dim unique As Integer() = RemoveDuplicates(numbers)
    Console.WriteLine(String.Join(", ", unique)) ' 1, 2, 3, 4
End Sub
Coding Round
35. Merge arrays

Merge arrays using List(Of T) or Concat.

  • List: New List(Of T)(arr1).AddRange(arr2)
  • LINQ: arr1.Concat(arr2).ToArray()
  • Generic: Function(Of T)
  • Complexity: O(n) time
vb
' Merge arrays in Visual Basic
Function MergeArrays(Of T)(arr1 As T(), arr2 As T()) As T()
    Dim result As New List(Of T)()
    result.AddRange(arr1)
    result.AddRange(arr2)
    Return result.ToArray()
End Function

Function MergeUnique(arr1 As Integer(), arr2 As Integer()) As Integer()
    Dim set1 As New HashSet(Of Integer)(arr1)
    For Each item As Integer In arr2
        set1.Add(item)
    Next
    Return set1.ToArray()
End Function

Sub Main()
    Dim arr1 As Integer() = {1, 2, 3}
    Dim arr2 As Integer() = {3, 4, 5}
    Dim merged As Integer() = MergeArrays(arr1, arr2)
    Console.WriteLine(String.Join(", ", merged)) ' 1, 2, 3, 3, 4, 5
    
    Dim unique As Integer() = MergeUnique(arr1, arr2)
    Console.WriteLine(String.Join(", ", unique)) ' 1, 2, 3, 4, 5
End Sub
Coding Round
36. Convert string to number

Convert string to number using Integer.TryParse.

  • TryParse: Integer.TryParse(str, result)
  • Return type: Integer?
  • Error handling: Returns Nothing on failure
  • Safe conversion: No exceptions thrown
vb
' Convert string to number in Visual Basic
Function StringToNumber(str As String) As Integer?
    Dim result As Integer
    If Integer.TryParse(str, result) Then
        Return result
    End If
    Return Nothing
End Function

Sub Main()
    Dim num As Integer? = StringToNumber("42")
    Console.WriteLine(num) ' 42
    num = StringToNumber("invalid")
    Console.WriteLine(num.HasValue) ' False
End Sub
Coding Round
37. Loop through dictionary

Iterate through dictionary using For Each.

  • For Each: For Each kvp As KeyValuePair(Of TKey, TValue) In dict
  • Keys: dict.Keys
  • Values: dict.Values
  • Return type: Void
vb
' Loop through dictionary in Visual Basic
Sub Main()
    Dim dict As New Dictionary(Of String, Object)() From {
        {"name", "Alice"},
        {"age", 25},
        {"city", "NYC"}
    }
    
    For Each kvp As KeyValuePair(Of String, Object) In dict
        Console.WriteLine(kvp.Key & " => " & kvp.Value)
    Next
End Sub
Coding Round
38. Delay function execution

Delay execution using Thread.Sleep or Task.Delay.

  • Thread.Sleep: Thread.Sleep(delayMs)
  • Task.Delay: Await Task.Delay(delayMs)
  • Async: Use Async/Await
  • Return type: Task or Void
vb
' Delay function execution in Visual Basic
Imports System.Threading

Sub DelayedExecution(delayMs As Integer, action As Action)
    Thread.Sleep(delayMs)
    action()
End Sub

Async Function DelayedAsync(delayMs As Integer) As Task
    Await Task.Delay(delayMs)
End Function

Sub Main()
    DelayedExecution(2000, Sub()
        Console.WriteLine("After 2 seconds")
    End Sub)
    
    ' Async version
    Dim task As Task = DelayedAsync(2000)
    task.Wait()
    Console.WriteLine("After 2 seconds (async)")
End Sub
Coding Round
39. HTTP GET request

Make HTTP GET requests using HttpClient.

  • HttpClient: New HttpClient()
  • GetAsync: Await client.GetAsync(url)
  • ReadAsStringAsync: Await response.Content.ReadAsStringAsync()
  • Return type: Task(Of String)
vb
' HTTP GET request in Visual Basic
Imports System.Net.Http

Async Function FetchData(url As String) As Task(Of String)
    Using client As New HttpClient()
        Dim response As HttpResponseMessage = Await client.GetAsync(url)
        response.EnsureSuccessStatusCode()
        Return Await response.Content.ReadAsStringAsync()
    End Using
End Function

Sub Main()
    Dim task As Task = MainAsync()
    task.Wait()
End Sub

Async Function MainAsync() As Task
    Dim data As String = Await FetchData("https://api.example.com/data")
    Console.WriteLine(data)
End Function
Coding Round
40. Create a promise-like Deferred

Create a Deferred using TaskCompletionSource(Of T).

  • TaskCompletionSource: New TaskCompletionSource(Of T)()
  • SetResult: tcs.SetResult(value)
  • SetException: tcs.SetException(ex)
  • Return type: Task(Of T)
vb
' Promise-like Deferred in Visual Basic
' Using TaskCompletionSource
Function CreateDeferred(shouldResolve As Boolean) As Task(Of String)
    Dim tcs As New TaskCompletionSource(Of String)()
    
    Task.Run(Sub()
        Thread.Sleep(1000)
        If shouldResolve Then
            tcs.SetResult("Success!")
        Else
            tcs.SetException(New Exception("Failed!"))
        End If
    End Sub)
    
    Return tcs.Task
End Function

Sub Main()
    Dim task As Task(Of String) = CreateDeferred(True)
    Try
        Dim result As String = task.Result
        Console.WriteLine(result)
    Catch ex As AggregateException
        Console.WriteLine("Error: " & ex.InnerException.Message)
    End Try
End Sub
Coding Round
41. Factorial

Calculate factorial using recursion or iteration.

  • Recursive: n * Factorial(n - 1)
  • Base case: n <= 1
  • Iterative: For loop
  • Return type: Integer
vb
' Factorial in Visual Basic
Function Factorial(n As Integer) As Integer
    If n <= 1 Then
        Return 1
    End If
    Return n * Factorial(n - 1)
End Function

Sub Main()
    Console.WriteLine(Factorial(5)) ' 120
End Sub
Coding Round
42. Fibonacci

Calculate Fibonacci using recursion, iteration, or memoization.

  • Recursive: Fibonacci(n - 1) + Fibonacci(n - 2)
  • Iterative: For loop with variables
  • Memoization: Dictionary(Of Integer, Integer)
  • Return type: Integer
vb
' Fibonacci in Visual Basic
Function Fibonacci(n As Integer) As Integer
    If n <= 1 Then
        Return n
    End If
    Return Fibonacci(n - 1) + Fibonacci(n - 2)
End Function

Sub Main()
    Console.WriteLine(Fibonacci(8)) ' 21
End Sub
Coding Round
43. FizzBuzz

FizzBuzz using if-else with modulo operations.

  • Modulo: i Mod 15
  • Order: Check 15 first
  • Loop: For i As Integer = 1 To n
  • Return type: Void
vb
' FizzBuzz in Visual Basic
Sub FizzBuzz(n As Integer)
    For i As Integer = 1 To n
        If i Mod 15 = 0 Then
            Console.WriteLine("FizzBuzz")
        ElseIf i Mod 3 = 0 Then
            Console.WriteLine("Fizz")
        ElseIf i Mod 5 = 0 Then
            Console.WriteLine("Buzz")
        Else
            Console.WriteLine(i)
        End If
    Next
End Sub

Sub Main()
    FizzBuzz(15)
End Sub
Coding Round
44. Find missing number

Find missing number using formula n*(n+1)/2 - sum.

  • Formula: total - sum
  • LINQ: arr.Sum()
  • Return type: Integer
  • Complexity: O(n) time
vb
' Find missing number in Visual Basic
Function FindMissing(arr As Integer()) As Integer
    Dim n As Integer = arr.Length + 1
    Dim total As Integer = n * (n + 1) / 2
    Dim sum As Integer = arr.Sum()
    Return total - sum
End Function

Sub Main()
    Dim numbers As Integer() = {1, 2, 4, 5, 6}
    Dim missing As Integer = FindMissing(numbers)
    Console.WriteLine(missing) ' 3
End Sub
Coding Round
45. Find duplicates

Find duplicates using HashSet(Of T).

  • HashSet: New HashSet(Of Integer)()
  • Track: seen.Contains(item)
  • Return type: Integer()
  • Complexity: O(n) time
vb
' Find duplicates in Visual Basic
Function FindDuplicates(arr As Integer()) As Integer()
    Dim seen As New HashSet(Of Integer)()
    Dim duplicates As New List(Of Integer)()
    For Each item As Integer In arr
        If seen.Contains(item) Then
            duplicates.Add(item)
        Else
            seen.Add(item)
        End If
    Next
    Return duplicates.ToArray()
End Function

Sub Main()
    Dim numbers As Integer() = {1, 2, 3, 2, 4, 3}
    Dim dups As Integer() = FindDuplicates(numbers)
    Console.WriteLine(String.Join(", ", dups)) ' 2, 3
End Sub
Coding Round
46. Sum of array

Calculate sum using LINQ or manual iteration.

  • LINQ: arr.Sum()
  • Manual: For Each loop
  • Return type: Integer
  • Complexity: O(n) time
vb
' Sum of array in Visual Basic
Function SumArray(arr As Integer()) As Integer
    Return arr.Sum()
End Function

Sub Main()
    Dim numbers As Integer() = {1, 2, 3, 4, 5}
    Dim sum As Integer = SumArray(numbers)
    Console.WriteLine(sum) ' 15
End Sub
Coding Round
47. Average of array

Calculate average using LINQ or manual division.

  • LINQ: arr.Average()
  • Manual: sum / arr.Length
  • Return type: Double
  • Empty array: Return 0.0
vb
' Average of array in Visual Basic
Function AverageArray(arr As Double()) As Double
    If arr.Length = 0 Then
        Return 0.0
    End If
    Return arr.Average()
End Function

Sub Main()
    Dim numbers As Double() = {1.0, 2.0, 3.0, 4.0, 5.0}
    Dim avg As Double = AverageArray(numbers)
    Console.WriteLine(avg) ' 3.0
End Sub
Coding Round
48. Sort array ascending

Sort using Array.Sort or LINQ.

  • Array.Sort: Array.Sort(arr)
  • LINQ: arr.OrderBy(Function(x) x).ToArray()
  • In-place: Modifies original array
  • Complexity: O(n log n)
vb
' Sort array ascending in Visual Basic
Sub SortAscending(arr As Integer())
    Array.Sort(arr)
End Sub

Sub Main()
    Dim numbers As Integer() = {5, 2, 8, 1, 9}
    SortAscending(numbers)
    Console.WriteLine(String.Join(", ", numbers)) ' 1, 2, 5, 8, 9
End Sub
Coding Round
49. Sort array descending

Sort descending using Array.Sort and Array.Reverse or LINQ.

  • Array.Sort/Reverse: Array.Sort(arr) : Array.Reverse(arr)
  • LINQ: arr.OrderByDescending(Function(x) x).ToArray()
  • In-place: Modifies original array
  • Complexity: O(n log n)
vb
' Sort array descending in Visual Basic
Sub SortDescending(arr As Integer())
    Array.Sort(arr)
    Array.Reverse(arr)
End Sub

Sub Main()
    Dim numbers As Integer() = {5, 2, 8, 1, 9}
    SortDescending(numbers)
    Console.WriteLine(String.Join(", ", numbers)) ' 9, 8, 5, 2, 1
End Sub
Coding Round
50. Flatten nested array

Flatten nested arrays using List(Of T) or LINQ.

  • List: New List(Of Integer)().AddRange(subList)
  • LINQ: arr.SelectMany(Function(x) x).ToArray()
  • Return type: Integer()
  • Complexity: O(n) time
vb
' Flatten nested array in Visual Basic
Function FlattenArray(arr As List(Of List(Of Integer))) As Integer()
    Dim result As New List(Of Integer)()
    For Each subList As List(Of Integer) In arr
        result.AddRange(subList)
    Next
    Return result.ToArray()
End Function

Sub Main()
    Dim nested As New List(Of List(Of Integer))() From {
        New List(Of Integer)() From {1, 2},
        New List(Of Integer)() From {3, 4},
        New List(Of Integer)() From {5, 6}
    }
    Dim flat As Integer() = FlattenArray(nested)
    Console.WriteLine(String.Join(", ", flat)) ' 1, 2, 3, 4, 5, 6
End Sub
Coding Round
51. Chunk array

Split array into chunks using List(Of List(Of T)).

  • Loop: For i As Integer = 0 To arr.Length - 1
  • Collect: current.Add(arr(i))
  • Return type: List(Of List(Of Integer))
  • Edge case: Handle last chunk
vb
' Chunk array in Visual Basic
Function ChunkArray(arr As Integer(), size As Integer) As List(Of List(Of Integer))
    Dim chunks As New List(Of List(Of Integer))()
    Dim current As New List(Of Integer)()
    For i As Integer = 0 To arr.Length - 1
        current.Add(arr(i))
        If (i + 1) Mod size = 0 Then
            chunks.Add(current)
            current = New List(Of Integer)()
        End If
    Next
    If current.Count > 0 Then
        chunks.Add(current)
    End If
    Return chunks
End Function

Sub Main()
    Dim numbers As Integer() = {1, 2, 3, 4, 5, 6}
    Dim chunks As List(Of List(Of Integer)) = ChunkArray(numbers, 2)
    For Each chunk As List(Of Integer) In chunks
        Console.WriteLine("[" & String.Join(", ", chunk) & "]")
    Next
End Sub
Coding Round
53. Quick sort

Quick sort using recursion and partitioning.

  • Algorithm: Choose pivot, partition, recurse
  • Time: O(n log n) average
  • Memory: Creates new arrays
  • Return type: Integer()
vb
' Quick sort in Visual Basic
Function QuickSort(arr As Integer()) As Integer()
    If arr.Length <= 1 Then
        Return arr
    End If
    Dim pivot As Integer = arr(0)
    Dim left As New List(Of Integer)()
    Dim right As New List(Of Integer)()
    For i As Integer = 1 To arr.Length - 1
        If arr(i) < pivot Then
            left.Add(arr(i))
        Else
            right.Add(arr(i))
        End If
    Next
    Return QuickSort(left.ToArray()).Concat({pivot}).Concat(QuickSort(right.ToArray())).ToArray()
End Function

Sub Main()
    Dim numbers As Integer() = {5, 3, 8, 4, 2, 7, 1, 6}
    Dim sorted As Integer() = QuickSort(numbers)
    Console.WriteLine(String.Join(", ", sorted))
End Sub
Coding Round
54. Merge sort

Merge sort using divide-and-conquer and merging.

  • Algorithm: Divide, sort, merge
  • Time: O(n log n)
  • Space: O(n) auxiliary space
  • Return type: Integer()
vb
' Merge sort in Visual Basic
Function MergeSort(arr As Integer()) As Integer()
    If arr.Length <= 1 Then
        Return arr
    End If
    Dim mid As Integer = arr.Length  2
    Dim left As Integer() = MergeSort(arr.Take(mid).ToArray())
    Dim right As Integer() = MergeSort(arr.Skip(mid).ToArray())
    Return Merge(left, right)
End Function

Function Merge(left As Integer(), right As Integer()) As Integer()
    Dim result As New List(Of Integer)()
    Dim i As Integer = 0
    Dim j As Integer = 0
    While i < left.Length And j < right.Length
        If left(i) <= right(j) Then
            result.Add(left(i))
            i += 1
        Else
            result.Add(right(j))
            j += 1
        End If
    End While
    While i < left.Length
        result.Add(left(i))
        i += 1
    End While
    While j < right.Length
        result.Add(right(j))
        j += 1
    End While
    Return result.ToArray()
End Function

Sub Main()
    Dim numbers As Integer() = {5, 3, 8, 4, 2, 7, 1, 6}
    Dim sorted As Integer() = MergeSort(numbers)
    Console.WriteLine(String.Join(", ", sorted))
End Sub
Coding Round
55. Bubble sort

Bubble sort with early termination.

  • Algorithm: Compare adjacent, swap
  • Time: O(n²) worst case
  • Optimization: Stop if no swaps
  • In-place: Modifies original array
vb
' Bubble sort in Visual Basic
Sub BubbleSort(ByRef arr As Integer())
    For i As Integer = 0 To arr.Length - 2
        Dim swapped As Boolean = False
        For j As Integer = 0 To arr.Length - i - 2
            If arr(j) > arr(j + 1) Then
                Dim temp As Integer = arr(j)
                arr(j) = arr(j + 1)
                arr(j + 1) = temp
                swapped = True
            End If
        Next
        If Not swapped Then
            Exit For
        End If
    Next
End Sub

Sub Main()
    Dim numbers As Integer() = {5, 3, 8, 4, 2, 7, 1, 6}
    BubbleSort(numbers)
    Console.WriteLine(String.Join(", ", numbers))
End Sub
Coding Round
56. Intersection of arrays

Find common elements using HashSet(Of T).

  • HashSet: New HashSet(Of Integer)(arr2)
  • Filter: set2.Contains(item)
  • Return type: Integer()
  • Complexity: O(n) time
vb
' Intersection of arrays in Visual Basic
Function Intersection(arr1 As Integer(), arr2 As Integer()) As Integer()
    Dim set2 As New HashSet(Of Integer)(arr2)
    Dim result As New List(Of Integer)()
    For Each item As Integer In arr1
        If set2.Contains(item) Then
            result.Add(item)
        End If
    Next
    Return result.ToArray()
End Function

Sub Main()
    Dim arr1 As Integer() = {1, 2, 3, 4}
    Dim arr2 As Integer() = {3, 4, 5, 6}
    Dim inter As Integer() = Intersection(arr1, arr2)
    Console.WriteLine(String.Join(", ", inter)) ' 3, 4
End Sub
Coding Round
57. Union of arrays

Combine arrays with unique elements using HashSet(Of T).

  • HashSet: New HashSet(Of Integer)(arr1)
  • Add: set1.Add(item)
  • Return type: Integer()
  • Complexity: O(n) time
vb
' Union of arrays in Visual Basic
Function Union(arr1 As Integer(), arr2 As Integer()) As Integer()
    Dim set1 As New HashSet(Of Integer)(arr1)
    For Each item As Integer In arr2
        set1.Add(item)
    Next
    Return set1.ToArray()
End Function

Sub Main()
    Dim arr1 As Integer() = {1, 2, 3}
    Dim arr2 As Integer() = {3, 4, 5}
    Dim uni As Integer() = Union(arr1, arr2)
    Console.WriteLine(String.Join(", ", uni)) ' 1, 2, 3, 4, 5
End Sub
Coding Round
58. Difference of arrays

Find elements in first array not in second using HashSet(Of T).

  • HashSet: New HashSet(Of Integer)(arr2)
  • Filter: Not set2.Contains(item)
  • Return type: Integer()
  • Complexity: O(n) time
vb
' Difference of arrays in Visual Basic
Function Difference(arr1 As Integer(), arr2 As Integer()) As Integer()
    Dim set2 As New HashSet(Of Integer)(arr2)
    Dim result As New List(Of Integer)()
    For Each item As Integer In arr1
        If Not set2.Contains(item) Then
            result.Add(item)
        End If
    Next
    Return result.ToArray()
End Function

Sub Main()
    Dim arr1 As Integer() = {1, 2, 3, 4}
    Dim arr2 As Integer() = {3, 4, 5, 6}
    Dim diff As Integer() = Difference(arr1, arr2)
    Console.WriteLine(String.Join(", ", diff)) ' 1, 2
End Sub
Coding Round
59. Group by property

Group items by property using Dictionary(Of String, List(Of T)).

  • Dictionary: New Dictionary(Of String, List(Of Item))
  • Loop: For Each item In items
  • Return type: Dictionary(Of String, List(Of Item))
  • Complexity: O(n) time
vb
' Group by property in Visual Basic
Class Item
    Public Property Type As String
    Public Property Name As String
End Class

Function GroupByProperty(items As List(Of Item), key As String) As Dictionary(Of String, List(Of Item))
    Dim groups As New Dictionary(Of String, List(Of Item))()
    For Each item As Item In items
        Dim keyValue As String = If(key = "type", item.Type, item.Name)
        If Not groups.ContainsKey(keyValue) Then
            groups(keyValue) = New List(Of Item)()
        End If
        groups(keyValue).Add(item)
    Next
    Return groups
End Function

Sub Main()
    Dim data As New List(Of Item)() From {
        New Item() With {.Type = "fruit", .Name = "apple"},
        New Item() With {.Type = "fruit", .Name = "banana"},
        New Item() With {.Type = "veg", .Name = "carrot"}
    }
    Dim groups As Dictionary(Of String, List(Of Item)) = GroupByProperty(data, "type")
    For Each kvp As KeyValuePair(Of String, List(Of Item)) In groups
        Console.WriteLine(kvp.Key & ": " & String.Join(", ", kvp.Value.Select(Function(i) i.Name)))
    Next
End Sub
Coding Round
60. Deep clone object

Deep clone by manually copying all fields and nested objects.

  • Manual: New User() With { ... }
  • Nested: Copy nested objects
  • Return type: User
  • Independent: Complete separate copy
vb
' Deep clone in Visual Basic
Class Address
    Public Property City As String
    Public Property Zip As String
End Class

Class User
    Public Property Name As String
    Public Property Address As Address
    
    Public Function DeepClone() As User
        Return New User() With {
            .Name = Me.Name,
            .Address = New Address() With {
                .City = Me.Address.City,
                .Zip = Me.Address.Zip
            }
        }
    End Function
End Class

Sub Main()
    Dim original As New User() With {
        .Name = "Alice",
        .Address = New Address() With {
            .City = "NYC",
            .Zip = "10001"
        }
    }
    Dim cloned As User = original.DeepClone()
    cloned.Name = "Bob"
    cloned.Address.City = "LA"
    
    Console.WriteLine("Original: " & original.Name & ", " & original.Address.City)
    Console.WriteLine("Cloned: " & cloned.Name & ", " & cloned.Address.City)
End Sub
Coding Round
61. Immutable update

Perform immutable updates by creating new objects.

  • New object: New State() With { ... }
  • Copy: Copy unchanged fields
  • Return type: State
  • Original: Remains unchanged
vb
' Immutable update in Visual Basic
Class User
    Public Property Name As String
    Public Property Age As Integer
End Class

Class State
    Public Property User As User
End Class

Function UpdateAge(state As State, newAge As Integer) As State
    Return New State() With {
        .User = New User() With {
            .Name = state.User.Name,
            .Age = newAge
        }
    }
End Function

Sub Main()
    Dim state As New State() With {
        .User = New User() With {
            .Name = "Alice",
            .Age = 25
        }
    }
    Dim newState As State = UpdateAge(state, 26)
    Console.WriteLine(state.User.Age) ' 25
    Console.WriteLine(newState.User.Age) ' 26
End Sub
Coding Round
62. Pipe function

Pipe composes functions from left to right.

  • Generic: Function(Of T)
  • Loop: For Each fn In fns
  • Return type: T
  • Direction: Left to right
vb
' Pipe function in Visual Basic
Function Pipe(Of T)(value As T, fns As List(Of Func(Of T, T))) As T
    Dim result As T = value
    For Each fn As Func(Of T, T) In fns
        result = fn(result)
    Next
    Return result
End Function

Function Double(x As Integer) As Integer
    Return x * 2
End Function

Function AddTen(x As Integer) As Integer
    Return x + 10
End Function

Function Square(x As Integer) As Integer
    Return x * x
End Function

Sub Main()
    Dim process As New List(Of Func(Of Integer, Integer))() From {
        AddressOf Double,
        AddressOf AddTen,
        AddressOf Square
    }
    Dim result As Integer = Pipe(5, process)
    Console.WriteLine(result) ' (5*2+10)^2 = 400
End Sub
Coding Round
63. Compose function

Compose functions from right to left.

  • Generic: Function(Of T)
  • Loop: For i = fns.Count - 1 To 0 Step -1
  • Return type: T
  • Direction: Right to left
vb
' Compose function in Visual Basic
Function Compose(fns As List(Of Func(Of Integer, Integer))) As Func(Of Integer, Integer)
    Return Function(x As Integer) As Integer
        Dim result As Integer = x
        For i As Integer = fns.Count - 1 To 0 Step -1
            result = fns(i)(result)
        Next
        Return result
    End Function
End Function

Function Double(x As Integer) As Integer
    Return x * 2
End Function

Function AddTen(x As Integer) As Integer
    Return x + 10
End Function

Function Square(x As Integer) As Integer
    Return x * x
End Function

Sub Main()
    Dim process As Func(Of Integer, Integer) = Compose(New List(Of Func(Of Integer, Integer))() From {
        AddressOf Square,
        AddressOf AddTen,
        AddressOf Double
    })
    Dim result As Integer = process(5)
    Console.WriteLine(result) ' (5*2+10)^2 = 400
End Sub
Coding Round
64. Memoization

Cache function results based on arguments using Dictionary(Of TKey, TValue).

  • Cache: New Dictionary(Of TKey, TValue)()
  • Check: cache.ContainsKey(key)
  • Return type: TValue
  • Trade-off: Memory for speed
vb
' Memoization in Visual Basic
Function Memoize(Of TKey, TValue)(fn As Func(Of TKey, TValue)) As Func(Of TKey, TValue)
    Dim cache As New Dictionary(Of TKey, TValue)()
    Return Function(key As TKey) As TValue
        If cache.ContainsKey(key) Then
            Return cache(key)
        End If
        Dim result As TValue = fn(key)
        cache(key) = result
        Return result
    End Function
End Function

Function Fibonacci(n As Integer) As Integer
    If n <= 1 Then
        Return n
    End If
    Return Fibonacci(n - 1) + Fibonacci(n - 2)
End Function

Sub Main()
    Dim fib As Func(Of Integer, Integer) = Memoize(AddressOf Fibonacci)
    Console.WriteLine(fib(10)) ' 55
End Sub
Coding Round
65. Once function

Ensure a function is called only once using a flag.

  • Flag: Dim called As Boolean = False
  • Result: Dim result As T
  • Generic: Function(Of T)
  • Use case: Initialization
vb
' Once function in Visual Basic
Function Once(Of T)(fn As Func(Of T)) As Func(Of T)
    Dim called As Boolean = False
    Dim result As T = Nothing
    Return Function() As T
        If Not called Then
            called = True
            result = fn()
        End If
        Return result
    End Function
End Function

Sub Main()
    Dim initialize As Func(Of Integer) = Once(Function()
        Console.WriteLine("Initialized")
        Return 42
    End Function)
    
    Console.WriteLine(initialize())
    Console.WriteLine(initialize())
End Sub
Coding Round
66. Debounce with leading edge

Debounce with leading edge using timestamp tracking.

  • Timestamp: Dim lastCall As DateTime = DateTime.Now
  • Check: (now - lastCall).TotalMilliseconds >= delayMs
  • Return type: Action(Of T)
  • Use case: Search input, API calls
vb
' Debounce in Visual Basic
Imports System.Threading

Function Debounce(Of T)(delayMs As Integer, action As Action(Of T)) As Action(Of T)
    Dim lastCall As DateTime = DateTime.Now
    Return Sub(arg As T)
        Dim now As DateTime = DateTime.Now
        If (now - lastCall).TotalMilliseconds >= delayMs Then
            lastCall = now
            action(arg)
        End If
    End Sub
End Function

Sub Main()
    Dim debounced As Action(Of String) = Debounce(1000, Sub(msg As String)
        Console.WriteLine("Executed: " & msg)
    End Sub)
    
    debounced("First")
    debounced("Second")
    debounced("Third")
End Sub
Coding Round
67. Throttle with leading edge

Throttle with leading edge using timestamp tracking.

  • Timestamp: Dim lastCall As DateTime = DateTime.Now
  • Check: (now - lastCall).TotalMilliseconds >= delayMs
  • Return type: Action(Of T)
  • Use case: Scroll events, resize
vb
' Throttle in Visual Basic
Imports System.Threading

Function Throttle(Of T)(delayMs As Integer, action As Action(Of T)) As Action(Of T)
    Dim lastCall As DateTime = DateTime.Now
    Return Sub(arg As T)
        Dim now As DateTime = DateTime.Now
        If (now - lastCall).TotalMilliseconds >= delayMs Then
            lastCall = now
            action(arg)
        End If
    End Sub
End Function

Sub Main()
    Dim throttled As Action(Of String) = Throttle(1000, Sub(msg As String)
        Console.WriteLine("Executed: " & msg)
    End Sub)
    
    throttled("First")
    throttled("Second")
    throttled("Third")
End Sub
Coding Round
68. Deep equal

Deep equality comparison using field-by-field comparison.

  • Field comparison: Compare each field
  • Nested: Compare nested objects
  • Return type: Boolean
  • Complexity: O(n) time
vb
' Deep equal in Visual Basic
Class Address
    Public Property City As String
    Public Property Zip As String
End Class

Class User
    Public Property Name As String
    Public Property Address As Address
End Class

Function DeepEqual(a As User, b As User) As Boolean
    If a.Name <> b.Name Then
        Return False
    End If
    If a.Address.City <> b.Address.City Then
        Return False
    End If
    If a.Address.Zip <> b.Address.Zip Then
        Return False
    End If
    Return True
End Function

Sub Main()
    Dim user1 As New User() With {
        .Name = "Alice",
        .Address = New Address() With {
            .City = "NYC",
            .Zip = "10001"
        }
    }
    Dim user2 As New User() With {
        .Name = "Alice",
        .Address = New Address() With {
            .City = "NYC",
            .Zip = "10001"
        }
    }
    Console.WriteLine(DeepEqual(user1, user2)) ' True
End Sub
Coding Round
69. Observable pattern

Observable pattern with subscribers and notifications.

  • Observable: Class Observable(Of T)
  • Subscribe: Sub Subscribe(callback As Action(Of T))
  • Notify: Sub Notify(data As T)
  • Generic: (Of T)
vb
' Observable pattern in Visual Basic
Class Observable(Of T)
    Private _subscribers As New List(Of Action(Of T))()
    
    Public Sub Subscribe(callback As Action(Of T))
        _subscribers.Add(callback)
    End Sub
    
    Public Sub Notify(data As T)
        For Each subscriber As Action(Of T) In _subscribers
            subscriber(data)
        Next
    End Sub
End Class

Sub Main()
    Dim observable As New Observable(Of String)()
    observable.Subscribe(Sub(data As String)
        Console.WriteLine("Observer 1: " & data)
    End Sub)
    observable.Subscribe(Sub(data As String)
        Console.WriteLine("Observer 2: " & data)
    End Sub)
    observable.Notify("Hello World")
End Sub
Coding Round
70. Singleton pattern

Singleton pattern using private constructor and shared instance.

  • Private constructor: Private Sub New()
  • Shared instance: Private Shared _instance As Singleton
  • Thread-safe: SyncLock _lock
  • Return type: Singleton
vb
' Singleton pattern in Visual Basic
Public Class Singleton
    Private Shared _instance As Singleton = Nothing
    Private Shared _lock As New Object()
    Private _data As New List(Of String)()
    
    Private Sub New()
    End Sub
    
    Public Shared Function GetInstance() As Singleton
        If _instance Is Nothing Then
            SyncLock _lock
                If _instance Is Nothing Then
                    _instance = New Singleton()
                End If
            End SyncLock
        End If
        Return _instance
    End Function
    
    Public Sub AddData(item As String)
        _data.Add(item)
    End Sub
    
    Public Function GetData() As List(Of String)
        Return _data
    End Function
End Class

Sub Main()
    Dim s1 As Singleton = Singleton.GetInstance()
    Dim s2 As Singleton = Singleton.GetInstance()
    s1.AddData("Hello")
    Console.WriteLine(String.Join(", ", s2.GetData())) ' Hello
End Sub
Coding Round
71. Factory pattern

Factory pattern using shared function and interfaces.

  • Factory function: Shared Function CreateUser(type As String, name As String) As IUser
  • Interface: Interface IUser
  • Select Case: Determine which type
  • Return type: IUser
vb
' Factory pattern in Visual Basic
Interface IUser
    Property Name As String
    Function GetRole() As String
End Interface

Class Admin
    Implements IUser
    
    Public Property Name As String Implements IUser.Name
    
    Public Function GetRole() As String Implements IUser.GetRole
        Return "admin"
    End Function
End Class

Class Guest
    Implements IUser
    
    Public Property Name As String Implements IUser.Name
    
    Public Function GetRole() As String Implements IUser.GetRole
        Return "guest"
    End Function
End Class

Class RegularUser
    Implements IUser
    
    Public Property Name As String Implements IUser.Name
    
    Public Function GetRole() As String Implements IUser.GetRole
        Return "regular"
    End Function
End Class

Class UserFactory
    Public Shared Function CreateUser(type As String, name As String) As IUser
        Select Case type
            Case "admin"
                Return New Admin() With {.Name = name}
            Case "guest"
                Return New Guest() With {.Name = name}
            Case Else
                Return New RegularUser() With {.Name = name}
        End Select
    End Function
End Class

Sub Main()
    Dim admin As IUser = UserFactory.CreateUser("admin", "Alice")
    Dim guest As IUser = UserFactory.CreateUser("guest", "Bob")
    Console.WriteLine(admin.Name & " role: " & admin.GetRole())
    Console.WriteLine(guest.Name & " role: " & guest.GetRole())
End Sub
Coding Round
72. Strategy pattern

Strategy pattern using interfaces and composition.

  • Strategy interface: Interface IPaymentStrategy
  • Context: Class PaymentContext
  • Set strategy: Sub SetStrategy(strategy As IPaymentStrategy)
  • Execute: Sub ExecutePayment(amount As Double)
vb
' Strategy pattern in Visual Basic
Interface IPaymentStrategy
    Sub Pay(amount As Double)
End Interface

Class CreditCardStrategy
    Implements IPaymentStrategy
    
    Public Sub Pay(amount As Double) Implements IPaymentStrategy.Pay
        Console.WriteLine("Paid $" & amount & " with Credit Card")
    End Sub
End Class

Class PayPalStrategy
    Implements IPaymentStrategy
    
    Public Sub Pay(amount As Double) Implements IPaymentStrategy.Pay
        Console.WriteLine("Paid $" & amount & " with PayPal")
    End Sub
End Class

Class CryptoStrategy
    Implements IPaymentStrategy
    
    Public Sub Pay(amount As Double) Implements IPaymentStrategy.Pay
        Console.WriteLine("Paid $" & amount & " with Crypto")
    End Sub
End Class

Class PaymentContext
    Private _strategy As IPaymentStrategy
    
    Public Sub New(strategy As IPaymentStrategy)
        _strategy = strategy
    End Sub
    
    Public Sub SetStrategy(strategy As IPaymentStrategy)
        _strategy = strategy
    End Sub
    
    Public Sub ExecutePayment(amount As Double)
        _strategy.Pay(amount)
    End Sub
End Class

Sub Main()
    Dim context As New PaymentContext(New CreditCardStrategy())
    context.ExecutePayment(100.0)
    
    context.SetStrategy(New PayPalStrategy())
    context.ExecutePayment(50.0)
End Sub
Coding Round
73. Observer pattern

Observer pattern with subject and observers.

  • Subject: Class Subject
  • Observer interface: Interface IObserver
  • Attach: Sub Attach(observer As IObserver)
  • Notify: Private Sub NotifyObservers()
vb
' Observer pattern in Visual Basic
Interface IObserver
    Sub Update(data As String)
End Interface

Class Subject
    Private _observers As New List(Of IObserver)()
    Private _state As String = ""
    
    Public Sub Attach(observer As IObserver)
        _observers.Add(observer)
    End Sub
    
    Public Sub Detach(observer As IObserver)
        _observers.Remove(observer)
    End Sub
    
    Public Sub SetState(state As String)
        _state = state
        NotifyObservers()
    End Sub
    
    Private Sub NotifyObservers()
        For Each observer As IObserver In _observers
            observer.Update(_state)
        Next
    End Sub
End Class

Class ConcreteObserver
    Implements IObserver
    
    Private _name As String
    
    Public Sub New(name As String)
        Me._name = name
    End Sub
    
    Public Sub Update(data As String) Implements IObserver.Update
        Console.WriteLine(_name & " received: " & data)
    End Sub
End Class

Sub Main()
    Dim subject As New Subject()
    Dim observer1 As New ConcreteObserver("Observer1")
    Dim observer2 As New ConcreteObserver("Observer2")
    
    subject.Attach(observer1)
    subject.Attach(observer2)
    subject.SetState("Hello World")
End Sub
Coding Round
74. Decorator pattern

Decorator pattern using wrapper classes.

  • Component: Interface ICoffee
  • Decorator: Class MilkDecorator Implements ICoffee
  • Chaining: Multiple decorators
  • Benefits: Add behavior dynamically
vb
' Decorator pattern in Visual Basic
Interface ICoffee
    Function GetCost() As Double
    Function GetDescription() As String
End Interface

Class SimpleCoffee
    Implements ICoffee
    
    Public Function GetCost() As Double Implements ICoffee.GetCost
        Return 5.0
    End Function
    
    Public Function GetDescription() As String Implements ICoffee.GetDescription
        Return "Coffee"
    End Function
End Class

Class MilkDecorator
    Implements ICoffee
    
    Private _coffee As ICoffee
    
    Public Sub New(coffee As ICoffee)
        Me._coffee = coffee
    End Sub
    
    Public Function GetCost() As Double Implements ICoffee.GetCost
        Return _coffee.GetCost() + 2.0
    End Function
    
    Public Function GetDescription() As String Implements ICoffee.GetDescription
        Return _coffee.GetDescription() & ", Milk"
    End Function
End Class

Class SugarDecorator
    Implements ICoffee
    
    Private _coffee As ICoffee
    
    Public Sub New(coffee As ICoffee)
        Me._coffee = coffee
    End Sub
    
    Public Function GetCost() As Double Implements ICoffee.GetCost
        Return _coffee.GetCost() + 1.0
    End Function
    
    Public Function GetDescription() As String Implements ICoffee.GetDescription
        Return _coffee.GetDescription() & ", Sugar"
    End Function
End Class

Sub Main()
    Dim coffee As ICoffee = New SimpleCoffee()
    coffee = New MilkDecorator(coffee)
    coffee = New SugarDecorator(coffee)
    Console.WriteLine(coffee.GetDescription()) ' Coffee, Milk, Sugar
    Console.WriteLine(coffee.GetCost()) ' 8.0
End Sub
Coding Round
75. Command pattern

Command pattern with execute and undo methods.

  • Command interface: Interface ICommand
  • Execute: Sub Execute()
  • Undo: Sub Undo()
  • Command manager: Class CommandManager
vb
' Command pattern in Visual Basic
Interface ICommand
    Sub Execute()
    Sub Undo()
End Interface

Class AddCommand
    Implements ICommand
    
    Private _receiver As List(Of Integer)
    Private _value As Integer
    
    Public Sub New(receiver As List(Of Integer), value As Integer)
        Me._receiver = receiver
        Me._value = value
    End Sub
    
    Public Sub Execute() Implements ICommand.Execute
        _receiver.Add(_value)
    End Sub
    
    Public Sub Undo() Implements ICommand.Undo
        _receiver.Remove(_value)
    End Sub
End Class

Class CommandManager
    Private _history As New List(Of ICommand)()
    
    Public Sub Execute(command As ICommand)
        command.Execute()
        _history.Add(command)
    End Sub
    
    Public Sub Undo()
        If _history.Count > 0 Then
            Dim command As ICommand = _history(_history.Count - 1)
            command.Undo()
            _history.RemoveAt(_history.Count - 1)
        End If
    End Sub
End Class

Sub Main()
    Dim receiver As New List(Of Integer)() From {1, 2, 3}
    Dim manager As New CommandManager()
    Dim cmd As New AddCommand(receiver, 4)
    
    manager.Execute(cmd)
    Console.WriteLine(String.Join(", ", receiver)) ' 1, 2, 3, 4
    manager.Undo()
    Console.WriteLine(String.Join(", ", receiver)) ' 1, 2, 3
End Sub
Coding Round
76. Memento pattern

Memento pattern for state capture and restoration.

  • Originator: Class Originator
  • Memento: Class Memento
  • Caretaker: Class Caretaker
  • Restore: Sub RestoreState(memento As Memento)
vb
' Memento pattern in Visual Basic
Class Memento
    Public Property State As String
End Class

Class Originator
    Public Property State As String
    
    Public Function SaveState() As Memento
        Return New Memento() With {.State = State}
    End Function
    
    Public Sub RestoreState(memento As Memento)
        State = memento.State
    End Sub
End Class

Class Caretaker
    Private _mementos As New List(Of Memento)()
    
    Public Sub AddMemento(memento As Memento)
        _mementos.Add(memento)
    End Sub
    
    Public Function GetMemento(index As Integer) As Memento
        Return _mementos(index)
    End Function
End Class

Sub Main()
    Dim originator As New Originator()
    Dim caretaker As New Caretaker()
    
    originator.State = "State 1"
    caretaker.AddMemento(originator.SaveState())
    
    originator.State = "State 2"
    caretaker.AddMemento(originator.SaveState())
    
    originator.State = "State 3"
    
    originator.RestoreState(caretaker.GetMemento(0))
    Console.WriteLine(originator.State) ' State 1
End Sub
Coding Round
77. Mediator pattern

Mediator pattern for centralized communication.

  • Mediator: Class Mediator
  • Colleague: Class Colleague
  • Register: Sub Register(colleague As Colleague)
  • Send: Sub Send(message As String, sender As Colleague)
vb
' Mediator pattern in Visual Basic
Class Mediator
    Private _colleagues As New List(Of Colleague)()
    
    Public Sub Register(colleague As Colleague)
        _colleagues.Add(colleague)
        colleague.SetMediator(Me)
    End Sub
    
    Public Sub Send(message As String, sender As Colleague)
        For Each colleague As Colleague In _colleagues
            If colleague IsNot sender Then
                colleague.Receive(message)
            End If
        Next
    End Sub
End Class

Class Colleague
    Public Property Name As String
    Private _mediator As Mediator
    
    Public Sub New(name As String)
        Me.Name = name
    End Sub
    
    Public Sub SetMediator(mediator As Mediator)
        _mediator = mediator
    End Sub
    
    Public Sub Send(message As String)
        _mediator.Send(message, Me)
    End Sub
    
    Public Sub Receive(message As String)
        Console.WriteLine(Name & " received: " & message)
    End Sub
End Class

Sub Main()
    Dim mediator As New Mediator()
    Dim alice As New Colleague("Alice")
    Dim bob As New Colleague("Bob")
    
    mediator.Register(alice)
    mediator.Register(bob)
    alice.Send("Hello Bob!")
End Sub
Coding Round
78. Chain of Responsibility

Chain of Responsibility using interfaces.

  • Handler interface: Interface IHandler
  • SetNext: Function SetNext(handler As IHandler) As IHandler
  • Handle: Function Handle(request As String) As String
  • Chain: auth.SetNext(logger)
vb
' Chain of Responsibility in Visual Basic
Interface IHandler
    Function SetNext(handler As IHandler) As IHandler
    Function Handle(request As String) As String
End Interface

Class AuthHandler
    Implements IHandler
    
    Private _next As IHandler = Nothing
    
    Public Function SetNext(handler As IHandler) As IHandler Implements IHandler.SetNext
        _next = handler
        Return handler
    End Function
    
    Public Function Handle(request As String) As String Implements IHandler.Handle
        If request.Contains("token") Then
            Console.WriteLine("Authentication passed")
            If _next IsNot Nothing Then
                Return _next.Handle(request)
            End If
            Return "Success"
        End If
        Console.WriteLine("Authentication failed")
        Return Nothing
    End Function
End Class

Class LoggerHandler
    Implements IHandler
    
    Private _next As IHandler = Nothing
    
    Public Function SetNext(handler As IHandler) As IHandler Implements IHandler.SetNext
        _next = handler
        Return handler
    End Function
    
    Public Function Handle(request As String) As String Implements IHandler.Handle
        Console.WriteLine("Logging request: " & request)
        If _next IsNot Nothing Then
            Return _next.Handle(request)
        End If
        Return "Logged"
    End Function
End Class

Sub Main()
    Dim auth As New AuthHandler()
    Dim logger As New LoggerHandler()
    auth.SetNext(logger)
    Dim result As String = auth.Handle("token:valid")
    Console.WriteLine(result)
End Sub
Coding Round
79. State pattern

State pattern using interfaces.

  • State interface: Interface IState
  • Context: Class Context
  • Handle: Sub Handle(context As Context)
  • Transitions: context.State = New ProcessingState()
vb
' State pattern in Visual Basic
Interface IState
    Sub Handle(context As Context)
End Interface

Class Context
    Public Property State As IState
    
    Public Sub New()
        State = New ReadyState()
    End Sub
    
    Public Sub Request()
        State.Handle(Me)
    End Sub
End Class

Class ReadyState
    Implements IState
    
    Public Sub Handle(context As Context) Implements IState.Handle
        Console.WriteLine("Ready: Waiting for input")
        context.State = New ProcessingState()
    End Sub
End Class

Class ProcessingState
    Implements IState
    
    Public Sub Handle(context As Context) Implements IState.Handle
        Console.WriteLine("Processing: Working on task")
        context.State = New CompletedState()
    End Sub
End Class

Class CompletedState
    Implements IState
    
    Public Sub Handle(context As Context) Implements IState.Handle
        Console.WriteLine("Completed: Task finished")
    End Sub
End Class

Sub Main()
    Dim context As New Context()
    context.Request() ' Ready
    context.Request() ' Processing
    context.Request() ' Completed
End Sub
Coding Round
80. Proxy pattern

Proxy pattern using interfaces.

  • Subject interface: Interface ISubject
  • Proxy: Class Proxy Implements ISubject
  • Check access: Private Function CheckAccess() As Boolean
  • Lazy loading: If _realSubject Is Nothing Then
vb
' Proxy pattern in Visual Basic
Interface ISubject
    Function Request() As String
End Interface

Class RealSubject
    Implements ISubject
    
    Public Function Request() As String Implements ISubject.Request
        Return "RealSubject: Handling request"
    End Function
End Class

Class Proxy
    Implements ISubject
    
    Private _realSubject As RealSubject = Nothing
    
    Public Function Request() As String Implements ISubject.Request
        If CheckAccess() Then
            If _realSubject Is Nothing Then
                _realSubject = New RealSubject()
            End If
            Return _realSubject.Request()
        End If
        Return "Proxy: Access denied"
    End Function
    
    Private Function CheckAccess() As Boolean
        Console.WriteLine("Proxy: Checking access")
        Return True
    End Function
End Class

Sub Main()
    Dim proxy As New Proxy()
    Console.WriteLine(proxy.Request())
End Sub
Coding Round
81. Flyweight pattern

Flyweight pattern for sharing objects using dictionary.

  • Flyweight: Class Flyweight
  • Factory: Class FlyweightFactory
  • Cache: Private _flyweights As New Dictionary(Of String, Flyweight)()
  • Get: Function GetFlyweight(sharedState As String) As Flyweight
vb
' Flyweight pattern in Visual Basic
Class Flyweight
    Public Property SharedState As String
    
    Public Sub New(sharedState As String)
        Me.SharedState = sharedState
    End Sub
    
    Public Sub Operation(uniqueState As String)
        Console.WriteLine("Shared: " & SharedState & ", Unique: " & uniqueState)
    End Sub
End Class

Class FlyweightFactory
    Private _flyweights As New Dictionary(Of String, Flyweight)()
    
    Public Function GetFlyweight(sharedState As String) As Flyweight
        If _flyweights.ContainsKey(sharedState) Then
            Return _flyweights(sharedState)
        End If
        Dim flyweight As New Flyweight(sharedState)
        _flyweights(sharedState) = flyweight
        Console.WriteLine("Creating new flyweight for: " & sharedState)
        Return flyweight
    End Function
End Class

Sub Main()
    Dim factory As New FlyweightFactory()
    Dim fw1 As Flyweight = factory.GetFlyweight("state1")
    Dim fw2 As Flyweight = factory.GetFlyweight("state1")
    Dim fw3 As Flyweight = factory.GetFlyweight("state2")
    fw1.Operation("unique1")
    fw2.Operation("unique2")
    fw3.Operation("unique3")
End Sub
Coding Round
82. Bridge pattern

Bridge pattern for separating abstraction from implementation.

  • Implementation interface: Interface IImplementation
  • Abstraction: Class Abstraction
  • Operation: Function Operation() As String
  • Composition: Protected _impl As IImplementation
vb
' Bridge pattern in Visual Basic
Interface IImplementation
    Function OperationImpl() As String
End Interface

Class ConcreteImplementationA
    Implements IImplementation
    
    Public Function OperationImpl() As String Implements IImplementation.OperationImpl
        Return "ConcreteImplementationA: Operation"
    End Function
End Class

Class ConcreteImplementationB
    Implements IImplementation
    
    Public Function OperationImpl() As String Implements IImplementation.OperationImpl
        Return "ConcreteImplementationB: Operation"
    End Function
End Class

Class Abstraction
    Protected _impl As IImplementation
    
    Public Sub New(impl As IImplementation)
        Me._impl = impl
    End Sub
    
    Public Function Operation() As String
        Return "Abstraction: Additional logic - " & _impl.OperationImpl()
    End Function
End Class

Sub Main()
    Dim implA As New ConcreteImplementationA()
    Dim implB As New ConcreteImplementationB()
    Dim abstraction1 As New Abstraction(implA)
    Dim abstraction2 As New Abstraction(implB)
    Console.WriteLine(abstraction1.Operation())
    Console.WriteLine(abstraction2.Operation())
End Sub
Coding Round
83. Adapter pattern

Adapter pattern for converting interfaces.

  • Target interface: Interface ITarget
  • Adaptee: Class Adaptee
  • Adapter: Class Adapter Implements ITarget
  • Request: Function Request() As String
vb
' Adapter pattern in Visual Basic
Interface ITarget
    Function Request() As String
End Interface

Class Adaptee
    Public Function SpecificRequest() As String
        Return "Adaptee: Specific Request"
    End Function
End Class

Class Adapter
    Implements ITarget
    
    Private _adaptee As Adaptee
    
    Public Sub New(adaptee As Adaptee)
        Me._adaptee = adaptee
    End Sub
    
    Public Function Request() As String Implements ITarget.Request
        Return _adaptee.SpecificRequest()
    End Function
End Class

Sub Main()
    Dim adaptee As New Adaptee()
    Dim adapter As New Adapter(adaptee)
    Console.WriteLine(adapter.Request())
End Sub
Coding Round
84. Facade pattern

Facade pattern for simplifying subsystems.

  • Subsystems: Class SubsystemA, SubsystemB, SubsystemC
  • Facade: Class Facade
  • Operation: Function Operation() As String
  • Composition: Private _a As New SubsystemA()
vb
' Facade pattern in Visual Basic
Class SubsystemA
    Public Function OperationA() As String
        Return "SubsystemA: Operation"
    End Function
End Class

Class SubsystemB
    Public Function OperationB() As String
        Return "SubsystemB: Operation"
    End Function
End Class

Class SubsystemC
    Public Function OperationC() As String
        Return "SubsystemC: Operation"
    End Function
End Class

Class Facade
    Private _a As New SubsystemA()
    Private _b As New SubsystemB()
    Private _c As New SubsystemC()
    
    Public Function Operation() As String
        Return _a.OperationA() & " + " & _b.OperationB() & " + " & _c.OperationC()
    End Function
End Class

Sub Main()
    Dim facade As New Facade()
    Console.WriteLine(facade.Operation())
End Sub
Coding Round
85. Composite pattern

Composite pattern for tree structures.

  • Component interface: Interface IComponent
  • Leaf: Class Leaf Implements IComponent
  • Composite: Class Composite Implements IComponent
  • Add: Sub Add(component As IComponent)
vb
' Composite pattern in Visual Basic
Interface IComponent
    Function Operation() As String
End Interface

Class Leaf
    Implements IComponent
    
    Private _name As String
    
    Public Sub New(name As String)
        Me._name = name
    End Sub
    
    Public Function Operation() As String Implements IComponent.Operation
        Return "Leaf " & _name & ": Operation"
    End Function
End Class

Class Composite
    Implements IComponent
    
    Private _name As String
    Private _children As New List(Of IComponent)()
    
    Public Sub New(name As String)
        Me._name = name
    End Sub
    
    Public Sub Add(component As IComponent)
        _children.Add(component)
    End Sub
    
    Public Function Operation() As String Implements IComponent.Operation
        Dim result As String = "Composite " & _name & ": ["
        For Each child As IComponent In _children
            result &= child.Operation() & ", "
        Next
        result &= "]"
        Return result
    End Function
End Class

Sub Main()
    Dim leaf1 As New Leaf("A")
    Dim leaf2 As New Leaf("B")
    Dim composite As New Composite("Root")
    composite.Add(leaf1)
    composite.Add(leaf2)
    Console.WriteLine(composite.Operation())
End Sub
Coding Round
86. Visitor pattern

Visitor pattern for adding operations without modifying elements.

  • Visitor interface: Interface IVisitor
  • Element interface: Interface IElement
  • Visit methods: Function VisitElementA(element As ElementA) As String
  • Accept: Function Accept(visitor As IVisitor) As String
vb
' Visitor pattern in Visual Basic
Interface IVisitor
    Function VisitElementA(element As ElementA) As String
    Function VisitElementB(element As ElementB) As String
End Interface

Interface IElement
    Function Accept(visitor As IVisitor) As String
End Interface

Class ElementA
    Implements IElement
    
    Public Property Data As String
    
    Public Sub New(data As String)
        Me.Data = data
    End Sub
    
    Public Function Accept(visitor As IVisitor) As String Implements IElement.Accept
        Return visitor.VisitElementA(Me)
    End Function
End Class

Class ElementB
    Implements IElement
    
    Public Property Data As String
    
    Public Sub New(data As String)
        Me.Data = data
    End Sub
    
    Public Function Accept(visitor As IVisitor) As String Implements IElement.Accept
        Return visitor.VisitElementB(Me)
    End Function
End Class

Class ConcreteVisitor
    Implements IVisitor
    
    Public Function VisitElementA(element As ElementA) As String Implements IVisitor.VisitElementA
        Return "Visiting ElementA with data: " & element.Data
    End Function
    
    Public Function VisitElementB(element As ElementB) As String Implements IVisitor.VisitElementB
        Return "Visiting ElementB with data: " & element.Data
    End Function
End Class

Sub Main()
    Dim visitor As New ConcreteVisitor()
    Dim elementA As New ElementA("A data")
    Dim elementB As New ElementB("B data")
    Console.WriteLine(elementA.Accept(visitor))
    Console.WriteLine(elementB.Accept(visitor))
End Sub
Coding Round
87. Iterator pattern

Iterator pattern for sequential access.

  • Iterator: Class Iterator(Of T)
  • Next: Function NextItem() As T
  • HasNext: Function HasNext() As Boolean
  • Collection: Class Collection(Of T)
vb
' Iterator pattern in Visual Basic
Class Iterator(Of T)
    Private _collection As List(Of T)
    Private _index As Integer = 0
    
    Public Sub New(collection As List(Of T))
        Me._collection = collection
    End Sub
    
    Public Function NextItem() As T
        If HasNext() Then
            Dim value As T = _collection(_index)
            _index += 1
            Return value
        End If
        Return Nothing
    End Function
    
    Public Function HasNext() As Boolean
        Return _index < _collection.Count
    End Function
End Class

Class Collection(Of T)
    Private _items As New List(Of T)()
    
    Public Sub Add(item As T)
        _items.Add(item)
    End Sub
    
    Public Function GetIterator() As Iterator(Of T)
        Return New Iterator(Of T)(_items)
    End Function
End Class

Sub Main()
    Dim collection As New Collection(Of Integer)()
    collection.Add(1)
    collection.Add(2)
    collection.Add(3)
    
    Dim iterator As Iterator(Of Integer) = collection.GetIterator()
    While iterator.HasNext()
        Console.WriteLine(iterator.NextItem())
    End While
End Sub
Coding Round
88. Template Method pattern

Template Method for algorithm skeletons.

  • AbstractClass: MustInherit Class AbstractClass
  • Template method: Function TemplateMethod() As String
  • Abstract method: Protected MustOverride Function Step2() As String
  • ConcreteClass: Class ConcreteClass Inherits AbstractClass
vb
' Template Method pattern in Visual Basic
MustInherit Class AbstractClass
    Public Function TemplateMethod() As String
        Return Step1() & " -> " & Step2() & " -> " & Step3()
    End Function
    
    Protected Overridable Function Step1() As String
        Return "Step 1"
    End Function
    
    Protected MustOverride Function Step2() As String
    
    Protected Overridable Function Step3() As String
        Return "Step 3"
    End Function
End Class

Class ConcreteClass
    Inherits AbstractClass
    
    Protected Overrides Function Step2() As String
        Return "Concrete Step 2"
    End Function
End Class

Sub Main()
    Dim concrete As New ConcreteClass()
    Console.WriteLine(concrete.TemplateMethod())
End Sub
Coding Round
89. Builder pattern

Builder pattern for constructing complex objects.

  • Builder: Class Builder
  • Director: Class Director
  • Product: Class Product
  • Build steps: Sub BuildStepA()
vb
' Builder pattern in Visual Basic
Class Product
    Private _parts As New List(Of String)()
    
    Public Sub Add(part As String)
        _parts.Add(part)
    End Sub
    
    Public Function ListParts() As String
        Return String.Join(", ", _parts)
    End Function
End Class

Class Builder
    Private _product As New Product()
    
    Public Sub Reset()
        _product = New Product()
    End Sub
    
    Public Sub BuildStepA()
        _product.Add("Part A")
    End Sub
    
    Public Sub BuildStepB()
        _product.Add("Part B")
    End Sub
    
    Public Function GetResult() As Product
        Return _product
    End Function
End Class

Class Director
    Private _builder As Builder
    
    Public Sub New(builder As Builder)
        Me._builder = builder
    End Sub
    
    Public Sub BuildMinimal()
        _builder.BuildStepA()
    End Sub
    
    Public Sub BuildFull()
        _builder.BuildStepA()
        _builder.BuildStepB()
    End Sub
End Class

Sub Main()
    Dim builder As New Builder()
    Dim director As New Director(builder)
    director.BuildMinimal()
    Dim product As Product = builder.GetResult()
    Console.WriteLine(product.ListParts()) ' Part A
End Sub
Coding Round
90. Prototype pattern

Prototype pattern for cloning objects.

  • Prototype: Class Prototype
  • Clone: Function Clone() As Prototype
  • Deep clone: Function DeepClone() As Prototype
  • Copy: New Dictionary(Of String, Integer)(Nested)
vb
' Prototype pattern in Visual Basic
Class Prototype
    Public Property Name As String
    Public Property Nested As Dictionary(Of String, Integer)
    
    Public Sub New(name As String, nested As Dictionary(Of String, Integer))
        Me.Name = name
        Me.Nested = nested
    End Sub
    
    Public Function Clone() As Prototype
        Return New Prototype(Name, New Dictionary(Of String, Integer)(Nested))
    End Function
    
    Public Function DeepClone() As Prototype
        Dim newNested As New Dictionary(Of String, Integer)()
        For Each kvp As KeyValuePair(Of String, Integer) In Nested
            newNested(kvp.Key) = kvp.Value
        Next
        Return New Prototype(Name, newNested)
    End Function
End Class

Sub Main()
    Dim original As New Prototype("Original", New Dictionary(Of String, Integer)() From {{"value", 42}})
    Dim copy As Prototype = original.Clone()
    copy.Nested("value") = 99
    Console.WriteLine(original.Nested("value")) ' 42
    
    Dim deepCopy As Prototype = original.DeepClone()
    deepCopy.Nested("value") = 100
    Console.WriteLine(original.Nested("value")) ' 42
End Sub
Coding Round
91. Error Handling

Error handling using custom exceptions and Try-Catch blocks.

  • Custom exception: Class ValidationException Inherits Exception
  • Try-Catch: Try...Catch ex As Exception
  • When clause: Catch ex As ValidationException When ex.Field = "age"
  • Finally: Finally block
vb
' Error Handling in Visual Basic
Module ErrorHandling
    ' Custom exception
    Public Class ValidationException
        Inherits Exception
        
        Public Property Field As String
        
        Public Sub New(field As String, message As String)
            MyBase.New(message)
            Me.Field = field
        End Sub
    End Class
    
    Sub ValidateAge(age As Integer)
        If age < 0 Then
            Throw New ValidationException("age", "Age cannot be negative")
        End If
        If age > 150 Then
            Throw New ValidationException("age", "Invalid age")
        End If
    End Sub
    
    Sub Main()
        Try
            ValidateAge(25)
            Console.WriteLine("Age is valid")
        Catch ex As ValidationException
            Console.WriteLine("Error in " & ex.Field & ": " & ex.Message)
        Catch ex As Exception
            Console.WriteLine("Error: " & ex.Message)
        End Try
        
        ' Using When clause
        Try
            ValidateAge(200)
        Catch ex As ValidationException When ex.Field = "age"
            Console.WriteLine("Age validation error: " & ex.Message)
        Catch ex As Exception
            Console.WriteLine("Other error: " & ex.Message)
        End Try
    End Sub
End Module
Coding Round
92. File I/O

File I/O operations using System.IO.

  • Write: File.WriteAllText()
  • Read: File.ReadAllText()
  • Append: File.AppendAllText()
  • Delete: File.Delete()
vb
' File I/O in Visual Basic
Imports System.IO

Module FileIO
    Sub Main()
        ' Write to file
        Dim content As String = "Hello, World!"
        File.WriteAllText("hello.txt", content)
        Console.WriteLine("File written successfully")
        
        ' Read from file
        Dim data As String = File.ReadAllText("hello.txt")
        Console.WriteLine("File content: " & data)
        
        ' Append to file
        File.AppendAllText("hello.txt", vbCrLf & "Appended line")
        Console.WriteLine("Appended successfully")
        
        ' Check if file exists
        If File.Exists("hello.txt") Then
            Console.WriteLine("File exists")
        End If
        
        ' Delete file
        File.Delete("hello.txt")
        Console.WriteLine("File deleted")
    End Sub
End Module
Coding Round
93. JSON Handling

JSON serialization using Newtonsoft.Json.

  • Serialize: JsonConvert.SerializeObject()
  • Deserialize: JsonConvert.DeserializeObject(Of T)()
  • Class: Public Class User
  • Properties: Match JSON keys
vb
' JSON Handling in Visual Basic
Imports Newtonsoft.Json

Module JSONHandling
    Public Class User
        Public Property Name As String
        Public Property Age As Integer
        Public Property Email As String
    End Class
    
    Sub Main()
        ' Serialize to JSON
        Dim user As New User() With {
            .Name = "Alice",
            .Age = 25,
            .Email = "alice@example.com"
        }
        Dim json As String = JsonConvert.SerializeObject(user)
        Console.WriteLine(json)
        
        ' Deserialize from JSON
        Dim jsonStr As String = "{""Name"":""Bob"",""Age"":30,""Email"":""bob@example.com""}"
        Dim parsed As User = JsonConvert.DeserializeObject(Of User)(jsonStr)
        Console.WriteLine("Name: " & parsed.Name & ", Age: " & parsed.Age)
    End Sub
End Module
Coding Round
94. Database Operations

Database operations using System.Data.SqlClient.

  • Connection: New SqlConnection(connectionString)
  • Command: New SqlCommand(sql, connection)
  • Execute: ExecuteNonQuery()
  • Query: ExecuteReader()
vb
' Database Operations in Visual Basic
Imports System.Data.SqlClient

Module DatabaseOps
    Sub Main()
        Dim connectionString As String = "Server=localhost;Database=test;Integrated Security=True"
        
        Using connection As New SqlConnection(connectionString)
            connection.Open()
            
            ' Create table
            Dim createCmd As New SqlCommand(
                "CREATE TABLE IF NOT EXISTS users (id INT IDENTITY(1,1) PRIMARY KEY, name NVARCHAR(100), age INT, email NVARCHAR(255))",
                connection
            )
            createCmd.ExecuteNonQuery()
            
            ' Insert data
            Dim insertCmd As New SqlCommand(
                "INSERT INTO users (name, age, email) VALUES (@name, @age, @email)",
                connection
            )
            insertCmd.Parameters.AddWithValue("@name", "Alice")
            insertCmd.Parameters.AddWithValue("@age", 25)
            insertCmd.Parameters.AddWithValue("@email", "alice@example.com")
            insertCmd.ExecuteNonQuery()
            
            ' Query data
            Dim queryCmd As New SqlCommand("SELECT * FROM users", connection)
            Dim reader As SqlDataReader = queryCmd.ExecuteReader()
            While reader.Read()
                Console.WriteLine("ID: " & reader("id") & ", Name: " & reader("name"))
            End While
        End Using
    End Sub
End Module
Coding Round
95. Testing

Testing using Assert and test attributes.

  • Test class: Public Class CalculatorTests
  • Test method: <Test> Public Sub TestAdd()
  • Assert: Assert.AreEqual()
  • Throws: Assert.Throws(Of T)()
vb
' Testing in Visual Basic
' Test class
Public Class CalculatorTests
    <Test>
    Public Sub TestAdd()
        Assert.AreEqual(5, Add(2, 3))
        Assert.AreEqual(0, Add(-1, 1))
    End Sub
    
    <Test>
    Public Sub TestDivide()
        Assert.AreEqual(5, Divide(10, 2))
        Assert.Throws(Of DivideByZeroException)(Sub() Divide(10, 0))
    End Sub
End Class

' Example functions
Function Add(a As Integer, b As Integer) As Integer
    Return a + b
End Function

Function Divide(a As Integer, b As Integer) As Integer
    Return a  b
End Function

Module Module1
    Sub Main()
        Console.WriteLine("Running tests...")
        ' In VB, tests are run with a test runner
    End Sub
End Module
Coding Round
96. LINQ

LINQ queries using query syntax and method syntax.

  • Query syntax: From num In numbers Where num Mod 2 = 0 Select num
  • Method syntax: numbers.Select(Function(x) x * 2)
  • Aggregation: Sum(), Average(), Max(), Min()
  • Ordering: Order By p.Age Descending
vb
' LINQ in Visual Basic
Imports System.Linq

Module LinqExamples
    Sub Main()
        Dim numbers As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
        
        ' Query syntax
        Dim evens = From num In numbers
                    Where num Mod 2 = 0
                    Select num
        
        Console.WriteLine("Evens: " & String.Join(", ", evens))
        
        ' Method syntax
        Dim doubled = numbers.Select(Function(x) x * 2).ToArray()
        Console.WriteLine("Doubled: " & String.Join(", ", doubled))
        
        ' Aggregation
        Dim sum = numbers.Sum()
        Dim avg = numbers.Average()
        Dim max = numbers.Max()
        Dim min = numbers.Min()
        
        Console.WriteLine("Sum: " & sum)
        Console.WriteLine("Avg: " & avg)
        Console.WriteLine("Max: " & max)
        Console.WriteLine("Min: " & min)
        
        ' Complex queries
        Dim people = {
            New With {.Name = "Alice", .Age = 25, .City = "NYC"},
            New With {.Name = "Bob", .Age = 30, .City = "LA"},
            New With {.Name = "Charlie", .Age = 35, .City = "Chicago"}
        }
        
        Dim adults = From p In people
                     Where p.Age >= 18
                     Order By p.Age Descending
                     Select p
                     
        For Each p In adults
            Console.WriteLine(p.Name & " (" & p.Age & ")")
        Next
    End Sub
End Module
Coding Round
97. Async/Await with LINQ

Combining async/await with LINQ queries.

  • Async function: Async Function FetchDataAsync() As Task(Of List(Of Integer))
  • Await: Await Task.Delay()
  • LINQ: From num In data Where num Mod 2 = 0
  • Return type: Task
vb
' Async/Await with LINQ in Visual Basic
Imports System.Linq

Module AsyncLinq
    Async Function FetchDataAsync() As Task(Of List(Of Integer))
        Await Task.Delay(1000)
        Return Enumerable.Range(1, 10).ToList()
    End Function
    
    Async Function ProcessDataAsync() As Task
        Dim data As List(Of Integer) = Await FetchDataAsync()
        
        ' LINQ with async
        Dim processed = From num In data
                        Where num Mod 2 = 0
                        Select num * 2
        
        For Each num In processed
            Console.WriteLine(num)
        Next
    End Function
    
    Sub Main()
        Dim task As Task = ProcessDataAsync()
        task.Wait()
    End Sub
End Module
Coding Round
98. Extension Methods

Extension methods using Extension attribute.

  • Extension module: Module StringExtensions
  • Extension attribute: <Extension()>
  • First parameter: str As String
  • Return type: Boolean or String
vb
' Extension Methods in Visual Basic
Imports System.Runtime.CompilerServices

Module StringExtensions
    <Extension()>
    Function IsValidEmail(str As String) As Boolean
        Return str.Contains("@") And str.Contains(".")
    End Function
    
    <Extension()>
    Function Truncate(str As String, maxLength As Integer) As String
        If str.Length <= maxLength Then
            Return str
        End If
        Return str.Substring(0, maxLength) & "..."
    End Function
End Module

Module NumberExtensions
    <Extension()>
    Function IsBetween(num As Integer, min As Integer, max As Integer) As Boolean
        Return num >= min And num <= max
    End Function
End Module

Module Module1
    Sub Main()
        Dim email As String = "test@example.com"
        Console.WriteLine(email.IsValidEmail()) ' True
        
        Dim text As String = "This is a very long string"
        Console.WriteLine(text.Truncate(10)) ' This is a...
        
        Console.WriteLine(5.IsBetween(1, 10)) ' True
    End Sub
End Module
Coding Round
99. Custom Collections

Custom collections implementing IEnumerable(Of T).

  • Implements: Implements IEnumerable(Of T)
  • Add: Public Sub Add(item As T)
  • GetEnumerator: Return _items.GetEnumerator()
  • LINQ-like methods: Where(), Select()
vb
' Custom Collections in Visual Basic
Public Class CustomCollection(Of T)
    Implements IEnumerable(Of T)
    
    Private _items As New List(Of T)()
    
    Public Sub Add(item As T)
        _items.Add(item)
    End Sub
    
    Public Function Count() As Integer
        Return _items.Count
    End Function
    
    Public Function GetEnumerator() As IEnumerator(Of T) Implements IEnumerable(Of T).GetEnumerator
        Return _items.GetEnumerator()
    End Function
    
    Private Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
        Return GetEnumerator()
    End Function
    
    ' Custom LINQ-like methods
    Public Function Where(predicate As Func(Of T, Boolean)) As CustomCollection(Of T)
        Dim result As New CustomCollection(Of T)()
        For Each item As T In _items
            If predicate(item) Then
                result.Add(item)
            End If
        Next
        Return result
    End Function
    
    Public Function Select(Of TResult)(selector As Func(Of T, TResult)) As CustomCollection(Of TResult)
        Dim result As New CustomCollection(Of TResult)()
        For Each item As T In _items
            result.Add(selector(item))
        Next
        Return result
    End Function
End Class

Module Module1
    Sub Main()
        Dim collection As New CustomCollection(Of Integer)()
        collection.Add(1)
        collection.Add(2)
        collection.Add(3)
        collection.Add(4)
        collection.Add(5)
        
        Dim evens = collection.Where(Function(x) x Mod 2 = 0)
        Dim doubled = collection.Select(Function(x) x * 2)
        
        Console.WriteLine("Evens: " & String.Join(", ", evens))
        Console.WriteLine("Doubled: " & String.Join(", ", doubled))
    End Sub
End Module
Coding Round
100. Visual Basic Best Practices

Best practices for writing clean, efficient Visual Basic code.

  • Option Strict On: Enforce type safety
  • Option Explicit On: Require variable declaration
  • Using statements: For resource management
  • Try-Catch: For error handling
  • LINQ: For data queries
  • Async/Await: For I/O operations
vb
' Visual Basic Best Practices
Module BestPractices
    ' 1. Use Option Strict On
    ' 2. Use Option Explicit On
    ' 3. Use meaningful names
    ' 4. Use type inference when appropriate
    ' 5. Use Using statements for resources
    ' 6. Use Try-Catch for error handling
    ' 7. Use LINQ for data queries
    ' 8. Use Async/Await for I/O operations
    ' 9. Use XML comments for documentation
    ' 10. Use constants for magic numbers
    
    Sub Main()
        ' Using statement for resources
        Using writer As New System.IO.StreamWriter("output.txt")
            writer.WriteLine("Hello, World!")
        End Using
        
        ' Try-Catch for error handling
        Try
            Dim result As Integer = Divide(10, 2)
            Console.WriteLine(result)
        Catch ex As DivideByZeroException
            Console.WriteLine("Division by zero!")
        End Try
        
        ' LINQ for queries
        Dim numbers As Integer() = {1, 2, 3, 4, 5}
        Dim evens = From num In numbers
                    Where num Mod 2 = 0
                    Select num
        Console.WriteLine("Evens: " & String.Join(", ", evens))
        
        ' Async/Await
        Dim task As Task = ProcessAsync()
        task.Wait()
    End Sub
    
    Async Function ProcessAsync() As Task
        Await Task.Delay(100)
        Console.WriteLine("Async operation completed")
    End Function
    
    Function Divide(a As Integer, b As Integer) As Integer
        If b = 0 Then
            Throw New DivideByZeroException()
        End If
        Return a  b
    End Function
End Module