0

Hello,

I have 2 classes A and B. A contains a reference to an object of type B. Depending on input from the user, an instance method objectOfTypeB.MethodB() is called, where objectOfTypeB is a field in the instantiated object objectOfTypeA.

I want that every time MethodB gets called on objectOfTypeB, a corresponding method, MethodA, gets also called on objectOfTypeA.

So, how can I get, inside objectOfTypeB.MethodB(), the reference to the "creator" of objectOfTypeB, that is, objectOfTypeA?

Thank you.

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by darkagn
0

You can create a two-way reference when you create the object B. Like so:

class A
{
   private B b;
   public A()
   {
      b = new B();
      b.SetA(this);
   }

   public void MethodA()
   {
      // do something
   }
}

class B
{
   private A a;
   public B()
   {
      a = null;
   }

   public void SetA(A a)
   {
      this.a = a;
   }

   public void MethodB()
   {
      // do something...

      // then call the MethodA
      if (a != null)
         a.MethodA();
      
   }
}

This should give you the general idea, however it is important to point out that such two-way references are prone to memory leaks. Therefore you should set B's reference to A back to null after you have finished using it. You can do this by setting the reference to null after the call to MethodA, or by implementing the IDisposable interface on both classes, or some other method...

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.