How to create a generic method in VB.NET

1 Answer

0 votes
Imports System

Module Program

    ' Generic method that swaps two values
    Public Sub Swap(Of T)(ByRef a As T, ByRef b As T)
        Dim temp As T = a
        a = b
        b = temp
    End Sub

    Sub Main()
        ' Swap integers
        Dim x As Integer = 10
        Dim y As Integer = 20
        Console.WriteLine($"Before swap: x = {x}, y = {y}")
        Swap(x, y)
        Console.WriteLine($"After swap:  x = {x}, y = {y}")

        Console.WriteLine()

        ' Swap strings
        Dim s1 As String = "Hello"
        Dim s2 As String = "World"
        Console.WriteLine($"Before swap: s1 = {s1}, s2 = {s2}")
        Swap(s1, s2)
        Console.WriteLine($"After swap:  s1 = {s1}, s2 = {s2}")

        Console.WriteLine()

        ' Swap doubles
        Dim d1 As Double = 1.5
        Dim d2 As Double = 3.7
        Console.WriteLine($"Before swap: d1 = {d1}, d2 = {d2}")
        Swap(d1, d2)
        Console.WriteLine($"After swap:  d1 = {d1}, d2 = {d2}")

        Console.ReadLine()
    End Sub

End Module



' run:
'
' Before swap: x = 10, y = 20
' After swap:  x = 20, y = 10
' 
' Before swap: s1 = Hello, s2 = World
' After swap:  s1 = World, s2 = Hello
' 
' Before swap: d1 = 1.5, d2 = 3.7
' After swap:  d1 = 3.7, d2 = 1.5
' 

 



answered 9 hours ago by avibootz
...