views:

24

answers:

1

VB.NET 2008 .NET 3.5

I have two base classes that are MustInherit (partial). Let's call one class OrderBase and the other OrderItemBase.

A specific type of order and order item would inherit from these classes. Let's call these WebOrder (inherits from OrderBase) and WebOrderItem (inherits from OrderItemBase).

Now, in the grand scheme of things WebOrder is a composite class containing a WebOrderItem, like so:

Public Class WebOrder
    Inherits OrderBase

    Public Property OrderItem() as WebOrderItem
    End Property

End Class

Public Class WebOrderItem
    Inherits OrderItemBase
End Class

In order to make sure any class that derives from OrderBase has the OrderItem property, I would like to do something like this in the OrderBase class:

Public MustInherit Class OrderBase
    Public MustOverride Property OrderItem() as Derivative(Of OrderItemBase)
End Class

In other words, I want the derived class to be forced to contain a property that returns a derivative of OrderItemBase.

Is this possible, or should I be using an entirely different approach?

A: 

Two options come to mind immediately:

First:

Public MustInherit Class OrderBase
    Public MustOverride Property OrderItem As OrderItemBase
End Class

Public Class WebOrder
    Inherits OrderBase

    Public Overrides Property OrderItem As OrderItemBase
End Class

which will make all derived classes have a property of type OrderItemBase (not a derived class of OrderItemBase)

Second:

Public MustInherit Class OrderBase(Of TItem As OrderItemBase)
    Public MustOverride Property OrderItem As TItem
End Class

Public Class WebOrder
    Inherits OrderBase(Of WebOrder)

    Public Overrides Property OrderItem As WebOrder
End Class

Note that this changes the class hierarchy such that there is no single base class for all your orders. You will have to make any method that works on the OrderBase(Of TItem) class generic.

Gideon Engelberth
Gideon,Your second solution is actually the one that I came up with on my own. I actually works very well for my situation.
Casey