How to declare a function argument that can accept any type in VB.NET

4 Answers

0 votes
Imports System
  
Class Program
    Public Shared Sub AcceptAnyType(Of T)(ByVal x As T)
        Dim s = TryCast(x, String)
        If s IsNot Nothing Then
            Console.WriteLine(s)
        Else
            Console.WriteLine("Not a string")
        End If
    End Sub
    Public Shared Sub Main()
        AcceptAnyType("A string")
        AcceptAnyType(809)
    End Sub
End Class
 
 
 
' run:
' 
' A string
' Not a string
'

 



answered Jul 31, 2025 by avibootz
edited Jul 31, 2025 by avibootz
0 votes
Imports System

Public Class Program
    Public Shared Sub AcceptAnyType(ByVal x As Object)
        Console.WriteLine($"The type of the argument is: {x.[GetType]()}")
    End Sub

    Public Shared Sub Main()
        AcceptAnyType(384)
        AcceptAnyType("ABCD")
        AcceptAnyType(3.14)
    End Sub
End Class
 
 
 
' run:
' 
' The type of the argument is: System.Int32
' The type of the argument is: System.String
' The type of the argument is: System.Double
'

 



answered Jul 31, 2025 by avibootz
0 votes
Imports System

Public Class Program
    Public Shared Sub AcceptAnyType(ByVal x As Object)
        If TypeOf x Is Integer Then
            Console.WriteLine("The argument is an integer.")
        ElseIf TypeOf x Is String Then
            Console.WriteLine("The argument is a string.")
        ElseIf TypeOf x Is Double Then
            Console.WriteLine("The argument is a double.")
        Else
            Console.WriteLine("The argument is of an unknown type.")
        End If
    End Sub

    Public Shared Sub Main()
        AcceptAnyType(384)
        AcceptAnyType("ABCD")
        AcceptAnyType(3.14)
    End Sub
End Class
 
 
 
' run:
' 
' The argument is an integer.
' The argument is a string.
' The argument is a double.
'

 



answered Jul 31, 2025 by avibootz
0 votes
Imports System

Public Class Program
    Public Shared Sub AcceptAnyType(Of T)(ByVal x As T)
        Console.WriteLine($"The type of the argument is: {GetType(T)}")
    End Sub

    Public Shared Sub Main()
        AcceptAnyType(384)
        AcceptAnyType("ABCD")
        AcceptAnyType(3.14)
    End Sub
End Class
 
 
 
' run:
' 
' The type of the argument is: System.Int32
' The type of the argument is: System.String
' The type of the argument is: System.Double
'

 



answered Jul 31, 2025 by avibootz
...