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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.