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)
            _RollingTotal += argVal
            If (_Values.Count < _RollCountMax) Then Exit Sub
            _RollingTotal -= _Values(0)
        End Sub

        Public ReadOnly Property Value As T
                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 :)

Edited 5 Years Ago by skatamatic: n/a

Maybe you can use a tricky solution.

Convert the values to be operated to the largest one, then operate and convert back to the original type.


return Ctype(Ctype(_rollingTotal,Long)/Ctype(_Values.Count,Long),T)

Be aware that when adding values, the result can be greater than the maximum allowed on the type being used. Also in substract you can get a value lower than the minimum.

Hope this helps

Edited 5 Years Ago by lolafuertes: n/a

This article has been dead for over six months. Start a new discussion instead.