Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out what class invoked a method

Tags:

c#

.net

class

Is there any way, in C#, for a class or method to know who (i.e. what class/ method) invoked it?

For example, I might have

class a{
   public void test(){
         b temp = new b();
         string output = temp.run();
   }
}

class b{
   public string run(){
        **CODE HERE**
   }
}

Output: "Invoked by the 'test' method of class 'a'."

like image 263
ChristianLinnell Avatar asked Dec 05 '22 06:12

ChristianLinnell


2 Answers

StackFrame

var frame = new StackFrame(1);

Console.WriteLine("Called by method '{0}' of class '{1}'",
    frame.GetMethod(),
    frame.GetMethod().DeclaringType.Name);
like image 147
Jimmy Avatar answered Dec 09 '22 15:12

Jimmy


You can look at the stack trace to determine who called it.

http://msdn.microsoft.com/en-us/library/system.environment.stacktrace.aspx

like image 44
Nippysaurus Avatar answered Dec 09 '22 14:12

Nippysaurus