954,557 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Generic Classes

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 :)

skatamatic
Posting Shark
959 posts since Nov 2007
Reputation Points: 403
Solved Threads: 129
 

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.

IE:

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

lolafuertes
Master Poster
798 posts since Oct 2008
Reputation Points: 120
Solved Threads: 167
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: