1

How can I invoke/call an object's method from another object method when both objects are created dynamically?

The situation is as follows:

I have two objects created dynamically each object correspond to a different class

objA
   Method1A()
objB
   Method1B()

I want to call objA's method1A() from objB's method1B().

How can I accomplish that / what approach do you recommended ?

Mark Hurd
  • 10,665
  • 10
  • 68
  • 101
armadillo.mx
  • 934
  • 1
  • 11
  • 17

2 Answers2

2

In order to invoke an instance method on some type you need an instance of that type. So if Method1B is supposed to invoke an instance method on objA you could pass this instance as parameter to the method:

public void Method1B(ObjA objA)
{
    objA.Method1A();
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I think this won't work if objA is created after objB, in that case how to implement it? – armadillo.mx Aug 08 '12 at 22:40
  • @armadillo.mx If that is possible then you have a cycle. You can't solve that with separate assemblies now, except when you can avoid cyclic declarations; then you can compile one assembly without the cyclic call, and then recompile with it, after the other assemblies have been built. You could try the same here, but unless you know the cycles and where you can temporarily break them, you have some analysis to do. – Mark Hurd Aug 09 '12 at 02:53
  • 1
    @Mark Hurd, you're right I think I'll need a different approach, thanks! – armadillo.mx Aug 14 '12 at 16:22
  • @armadillo.mx In that case I've upped my comment to an answer. – Mark Hurd Aug 14 '12 at 17:01
1

If it is possible that "objA is created after objB" then you have a cycle. You can't solve that with separate assemblies now, except when you can avoid cyclic declarations; then you can compile one assembly without the cyclic call, and then recompile with it, after the other assemblies have been built. You could try the same here, but unless you know the cycles and where you can temporarily break them, you have some analysis to do.

Note this question asks for and gets approaches similar to mine for cyclic dependencies between normal assemblies.

Community
  • 1
  • 1
Mark Hurd
  • 10,665
  • 10
  • 68
  • 101