How to create a generic class with a generic method in VB.NET

1 Answer

0 votes
Imports System

' Generic class
Class Generic(Of T)
    Private gVariable As T

    Public Sub New(gValue As T)
        Me.gVariable = gValue
    End Sub

    Public Sub Print()
        Console.WriteLine(Me.gVariable)
    End Sub
End Class

Module Program

    ' Generic method that creates a Generic(Of T) instance
    Public Function CreateGeneric(Of T)(value As T) As Generic(Of T)
        Return New Generic(Of T)(value)
    End Function

    ' Generic method that creates any type T with a parameterless constructor
    Public Function CreateInstance(Of T As {New})() As T
        Return New T()
    End Function

    Sub Main()
        Dim g1 = CreateGeneric(12)
        Dim g2 = CreateGeneric("C# Programming")
        Dim g3 = CreateGeneric(3.14F)
        Dim g4 = CreateGeneric(345.8916)

        g1.Print()
        g2.Print()
        g3.Print()
        g4.Print()

        Console.ReadLine()
    End Sub

End Module



' run:
'
' 12
' C# Programming
' 3.14
' 345.8916
' 

 



answered 19 hours ago by avibootz
...