Link to home
Start Free TrialLog in
Avatar of Onthrax
OnthraxFlag for Netherlands

asked on

Determining the calling function name.

Simple situation:

public function foo() as boolean
    bar()
end function

public function foo2() as boolean
    bar()
end function

public sub bar()
   'code to determine whether the function was called from foo or foo2
end sub

Which code would I place in the sub bar() to determine the calling function, without having to send it to the sub manually?
Avatar of Deathrace
Deathrace
Flag of India image

hey , i got a general idea,, is the below code helps you.

string whereimcalled = null; //declare globally
 
public function foo() as boolean
{
   whereimcalled = "Hey its method foo"; 
}
 
public function foo2() as boolean
{
  whereimcalled ="Hey its method foo2";
}
 
public subbar()
{
   // evaluate the string variable///
}
 
}

Open in new window

Avatar of cauos
cauos

you have to choices; you can pass extra parameter to the called function and then check the value of the passed parameter.
or you can use stacktrace class to know which is the calling function
  private void f1()
        {
            calledfunction();
        }
        private void f2()
        {
            calledfunction();
        }
        private void calledfunction()
        {
 
            System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1);
            System.Diagnostics.StackFrame sf = st.GetFrame(0);
            string msg =sf.GetMethod().Name;
            MessageBox.Show(msg);
 
        }

Open in new window

Have a look at the StackFrame and StackTrace classes.  I'm not sure what you're trying to achieve though.  If the function does something different based on who is calling it, then it should really have another function to run the different code....
ASKER CERTIFIED SOLUTION
Avatar of cauos
cauos

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Onthrax

ASKER

Thanks all for replying.

The stacktrace solution will work just fine without any extra manual settings. Great!

Cheers :)