Corey Ogburn
Corey Ogburn

Reputation: 24769

Determine what class called a method?

I have an application in mind, but I am not sure how to do this. Say I have some publically accessible method in a DLL file that takes no parameters. Is it possible for this method to know what called it? Can it tell if it were called from a static or instantiated context? From a specific class? What can a method know about how it's being called?

Upvotes: 7

Views: 2589

Answers (3)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

You can get caller information from a stack trace:

StackTrace stackTrace = new StackTrace();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();

It is possible for this method to know what called it:

string typeName = methodBase.DeclaringType.Name;
string methodName = methodBase.Name;

It can tell if it were called from a static or instantiated context:

bool isStaticCall = methodBase.IsStatic

From a specific class:

bool isGeneric = methodBase.DeclaringType.IsGenericType;

Upvotes: 7

jgauffin
jgauffin

Reputation: 101192

You can just do this:

var callingClass = new StackFrame(1).GetMethod().ReflectedType;

The 1 tells the constructor to skip the currently executing method.

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727097

If your program has sufficient privileges, it can construct a StackTrace and examine it frame-by-frame to determine who is the caller. This will get you the calling method, the calling class, and so on.

Upvotes: 2

Related Questions