Is it possible to restrict instantiation of an object to only one other (parent) object in VB.NET?

Posted by Casey on Stack Overflow See other posts from Stack Overflow or by Casey
Published on 2010-04-27T16:23:45Z Indexed on 2010/04/27 16:33 UTC
Read the original article Hit count: 273

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:

  1. Can not be instantiated as a stand alone object; requires Order to exist.

  2. Must be public so that any other object can access it's properties/methods through the Order object. e.g. Order.OrderItem(0).ProductID.

  3. 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?

© Stack Overflow or respective owner

Related posts about vb.net

Related posts about instantiation