2

I have the following scenario in C#

public class classA
{
public int fieldA = 1;

public classA()
{
    classB b=new classB();
    b.Execute();
}
}


public class classB
{
    public Execute() 
    {
        //I can get the type of classA using
        FieldInfo fi = stackTrace.GetFrame(1).GetMethod().DeclaringType
    }
}

The question is how do I get the reference of classA that invoked the Execute in the instance of classB?

I tried using reflection but could not find any way to do it.

Any help would be much appreciated

Thousand
  • 6,562
  • 3
  • 38
  • 46
user1466108
  • 151
  • 1
  • 4
  • 1
    possible duplicate of [Can I get calling instance from within method via reflection/diagnostics?](http://stackoverflow.com/questions/97193/can-i-get-calling-instance-from-within-method-via-reflection-diagnostics) – V4Vendetta Jun 19 '12 at 10:51
  • Is it an acceptable design that `classB` is provided a reference to `classA` in either its constructor or `Execute` method as a parameter? – Chris Sinclair Jun 19 '12 at 10:52
  • the Execute method is invoked by a number of other objects and I do not have the option to modify it or overload it – user1466108 Jun 19 '12 at 11:33

2 Answers2

3

You can send a the reference of A to B in execute method like this:

b.Execute(this);

you can reach the object A by this way.

Ozgur Dogus
  • 911
  • 3
  • 14
  • 38
1

Change class B like this

public class B
{
    public Execute(A aObj) 
    {
        //class A Object is available here


    }

}

Change Class A like this

public class A

{
   public A()
        {

            B b = new B();
            b.Execute(this);
        }
}
MSUH
  • 872
  • 2
  • 9
  • 20