Vb.net – How to make Parameters of VB.NET function as Generic type

functiongeneric-programminggenericsvb.net

I have a VB.NET function as below, the parameter 'x' that is passed to the function is of Type 'Single'. However, I want to write the function so that it can accept any numeric type such as 'Single', 'Double' and 'Integer'. I know one way of doing that is to write 3 functions with the same names, but it would be so tedious. Can anyone suggest any idea? Thank you.

Public Function Square(x As Single) As Single
  Return x * x
End Function

Best Solution

try following method

Public Function Square(Of T)(ByVal x As Object) As T
    Dim b As Object = Val(x) * Val(x)
    Return CType(b, T)
End Function

You can use above function like this

Dim p As Integer = Square(Of Integer)(10)
Dim d As Double = Square(Of Double)(1.5)