I am trying to write a somewhat generic class for calculating rolling averages. It's generic in the sense that it needs to support all numeric datatypes (int, double, short and long). I'm a bit of a noobie to VB.Net and have run into a problem:
Public Class RollingAverage(Of T)
Private _Values As List(Of T)
Private _RollCountMax As Long
Private _RollingTotal As T
Public Sub New(Optional ByVal argRollCountMax As Long = 15)
_RollCountMax = argRollCountMax
Dim dataTest As T
If (Not ((TypeOf (dataTest) Is Integer) Or (TypeOf (dataTest) Is Double) Or (TypeOf (dataTest) Is Short) Or (TypeOf (dataTest) Is Long))) Then
Throw New Exception("Rolling average does not support non numeric datatypes")
End If
_Values = New List(Of T)
End Sub
Public Sub AddValue(ByVal argVal As T)
_Values.Add(argVal)
_RollingTotal += argVal
If (_Values.Count < _RollCountMax) Then Exit Sub
_RollingTotal -= _Values(0)
_Values.RemoveAt(0)
End Sub
Public ReadOnly Property Value As T
Get
Return (_RollingTotal / _Values.Count)
End Get
End Property
End Class
Since T does not have a + or / operator defined, I get an error on the Return (_RollingTotal / _Values.Count)
, _RollingTotal += argVal
, and _RollingTotal -= _Values(0)
lines. I am wondering how to go about doing this - is there a common interface for numeric types? (I couldn't find one...) Any help would be greatly appreciated :)