.NET – Obtain Reference to Parent Object During Instantiation

netvb.net

I have a situation where a custom class is a property of another class.

What I need to be able to do, if it is possible at all, is obtain a reverse to the "parent" class (ie the the class that holds the current class as a property).

For Instance:

Public Class Class1
  ...
  public readonly property Prop11 as Class2
  public property Prop12 as String
  ...
End Class

Public Class Class2
  ...
  private _par as Class1
  private _var21 as string
  ...
  Public Sub New(...)
    me._par = ????
    ...
  End Sub
  public readonly property Prop21 as string
    Get
      return me._par.Prop12 & me._var21
    End Get
  End Property
  ...
End Class

Ultimately, I am trying to access other properties within Class1 from Class2 as they do have substance for information from within Class2. There are several other classes within Class1 that provide descriptive information to other classes contained within it as properties but the information is not extensible to all of the classes through Inheritance, as Class1 is being used as a resource bin for the property classes and the application itself.

Diagram, lazy design ;):

Application <- Class1.Prop12
Application <- Class1.Prop11.Prop21

Question:

Is it possible to get a recursion through this design setup?

Best Answer

Well, your design has problems, that's certain, and you've obfuscated the problem a bit too much here.

What I can suggest, based on what you've given, is that, instead of this:

class1.Prop12.Prop21

do this:

class1.WrappedProp

where Class1 implements WrappedProp like this:

Public Class Class1
    ...
    Public readonly property WrappedProp as string
        Get
            return me.Prop12 & myChild.Var21
        End Get
    End Property
    ...
End Class

That is to say that the "application" (or whatever object holds a reference to your class1/parent) should not access the child class (or, know about it at all for that matter). From what I can tell, what you're really doing is providing some kind of container or wrapper with your parent class, but not completely wrapping or containing the child type.

Related Topic