Inherit SortedDictionary

Posted on


As an example, suppose I had a large amount of data about a set of Restaurants for a large set of Dates in a database that I need to analyze / output to the user.

I have a custom class that holds the data for each restaurant for each date:

Public Class DateData
    Public Property Var1 As Double = 0
    Public Property Var2 As Double = 0
    Public Property Var3 As Double = 0
    Public Property Var4 As Double = 0

    Public Sub Sub1()
    End Sub

   ... etc ....
End Class

And since I am getting this data for each date (and since date-order does matter for my calculations), I have the following class set up too (where most of the work / calculation is done):

Public Class RestaurantData
    Inherits SortedDictionary(Of Date, DateData)

   Public Property Name As String
   Public Property RestaurantLevelData1 As Double = 0
   Public Property RestaurantLevelData2 As Double = 0

   Public Sub New(ByVal strName As String, ByVal DatesList As List(Of Date))
       _Name = strName
       For Each daDate As Date In DatesList
   End Sub

   Public Overloads Sub Add(ByVal daDate As Date)
        MyBase.Add(daDate, New DateData)
   End Sub

   Public Sub Sub1()
       For i As Integer = 0 To Me.Keys.Count - 1
           Dim daDate As Date = Me.Keys(i)
           .... etc ....
   End Sub

   ... etc ....
End Class

And, finally, since this is for a large amount of restaurants, I have a class which holds this Dictionary on a restaurant levele:

Public Class RestaurantsDict
    Inherits Dictionary(Of String, RestaurantData)

   Public Overloads Sub Add(ByVal strName As String, ByVal Dates As List(Of Date))
       MyBase.Add(strName, New RestaurantData(strName, Dates))
   End Sub
End Class

I have 2 main questions:

  1. Is this a good way to set this up? My original code consisted of dozens of

    Dictionary(Of String, SortedDictionary(Of Date, Double))

    But I am a fairly novice programmer and would love to know if there is a more efficient architecture for what I am trying to achieve.

  2. The way I am currently setting this up is very hard to debug. For example, the Count property of my RestaurantData throws an exception of type System.TypeLoadException.


Inheriting from collections is rarely a good practice. In your case it’s better to have a private collection (SortedDictionary in your case), and populate it as needed (in other words it’s better to use delegation than inheritance here).

The reason why inheriting is not so good here is that your class will expose a lot of functionality that users of RestaurantData aren’t actually interested in.

Leave a Reply

Your email address will not be published. Required fields are marked *