In VB.NET if I want to have an extension method for numerical variables of different types (Integer, Long, Decimal, Double) I always have to define multiple methods for these:
<Extension()> Public Function Add(a As Integer, b As Integer) As Integer
Return a + b
End Function
<Extension()> Public Function Add(a As Long, b As Long) As Long
Return a + b
End Function
<Extension()> Public Function Add(a As Double, b As Double) As Double
Return a + b
End Function
<Extension()> Public Function Add(a As Decimal, b As Decimal) As Decimal
Return a + b
End Function
Now for one single operation this is alright, but the more methods I want to create the more duplicates I have do to, too.
Is there a generic way to do so? I would love to see something like this (pseudo-code):
<Extension()> _
Public Function Add(Of T As Numeric)(a As T, b As T) As T
Return a + b
End Function
Or is there any other concept for doing so?
This cannot be done, because you cannot constrain a generic type to a group of numeric types (Integer, Long, Decimal, Double). The problem is that there is no IArithmetic interface that you could you use to constrain T to, therefore you cannot write this:
' This does not work because IArithmetic does not exist
<Extension()> _
Public Function Add(Of T As IArithmetic)(a As T, b As T) As T
Return a + b
End Function
However, you can join the cause to convince Microsoft to implement this by the Microsoft Feedback Center and proposing and/or commenting on similar requests.
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