Suppose I want to write a function similar to the following (as usual, a trivial example for illustrative purposes):
Public Function calcSqSum(Of T)(ByVal list As IEnumerable(Of T)) As T
Dim sumSq As T
For Each item As T In list
sumSq += (item * item)
Next
Return sumSq
End Function
As you can probably guess, this function raises an error because the universal object is not guaranteed to implement the + operator. However, as far as I know, any numeric type (integer, double, decimal, etc.) will be.
Is there a way to write a (quasi) generic function that can take any number type without having to explicitly overload the function for each such type independently?
Alternatively, I believe that an equally acceptable solution would be to somehow check if the type implements the + operator (or any operator that is usually associated with numeric types and used by the function).
source
share