Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Parameters of VB.NET function as Generic type?

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
like image 268
N.T.C Avatar asked Aug 12 '14 01:08

N.T.C


2 Answers

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)
like image 145
Shell Avatar answered Sep 19 '22 17:09

Shell


You can constrain the generic type by IConvertible and Structure. The following data types implements the IConvertible interface:

  • System.Boolean
  • System.Byte
  • System.Char
  • System.DateTime
  • System.DBNull
  • System.Decimal
  • System.Double
  • System.Enum
  • System.Int16
  • System.Int32
  • System.Int64
  • System.SByte
  • System.Single
  • System.String
  • System.UInt16
  • System.UInt32
  • System.UInt64

Here's a rewrite of the code found in the link provided by SLaks:

Public Function Square(Of T As {IConvertible, Structure})(x As T) As T
    'TODO: If (GetType(T) Is GetType(Date)) Then Throw New InvalidOperationException()
    Dim left As ParameterExpression = Expression.Parameter(GetType(T), "x")
    Dim right As ParameterExpression = Expression.Parameter(GetType(T), "x")
    Dim body As BinaryExpression = Expression.Multiply(left, right)
    Dim method As Func(Of T, T, T) = Expression.Lambda(Of Func(Of T, T, T))(body, left, right).Compile()
    Return method(x, x)
End Function

Reference: https://jonskeet.uk/csharp/miscutil/usage/genericoperators.html

like image 41
Bjørn-Roger Kringsjå Avatar answered Sep 21 '22 17:09

Bjørn-Roger Kringsjå