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
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)
You can constrain the generic type by IConvertible
and Structure
. The following data types implements the IConvertible interface:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With