Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get invoker class of this method

Tags:

c#

is it possible?

i want to get the name of class (like foo) which is invoking my method (like myMethod)

(and the method is in another class(like i))

like:

class foo
{
    i mc=new i;
    mc.mymethod();

}
class i
{
    myMethod()
    {........
       Console.WriteLine(InvokerClassName);// it should writes foo
    }
}

thanks in advance

like image 303
Mohsen Avatar asked Dec 28 '22 20:12

Mohsen


1 Answers

You can use StackTrace to work out the caller - but that's assuming there's no inlining going on. Stack traces aren't always 100% accurate. Something like:

StackTrace trace = new StackTrace();
StackFrame frame = trace.GetFrame(1); // 0 will be the inner-most method
MethodBase method = frame.GetMethod();
Console.WriteLine(method.DeclaringType);
like image 57
Jon Skeet Avatar answered Jan 08 '23 15:01

Jon Skeet