Is it possible to restrict instantiation of an object to only one other (parent) object in VB.NET?
- by Casey
VB 2008 .NET 3.5
Suppose we have two classes, Order and OrderItem, that represent some type of online ordering system. OrderItem represents a single line item in an Order. One Order can contain multiple OrderItems, in the form of a List(of OrderItem).
Public Class Order
Public Property MyOrderItems() as List(of OrderItem)
End Property
End Class
It makes sense that an OrderItem should not exist without an Order. In other words, an OrderItem class should not be able to be instantiated on its own, it should be dependent on an Order class to contain it and instantiate it. However, the OrderItem should be public in scope so that it's properties are accessible to other objects. So, the requirements for OrderItem are:
Can not be instantiated as a stand alone object; requires Order to exist.
Must be public so that any other object can access it's properties/methods through the Order object. e.g. Order.OrderItem(0).ProductID.
OrderItem should be able to be passed to other subs/functions that will operate on it.
How can I achieve these goals? Is there a better approach?