DotNetStudent
DotNetStudent

Reputation: 899

Retrieve Calling Method & Metadata from Delegate

Is it possible to retrieve from inside a given method any information about the method that called it?

public void MethodOne()
{
   for (int nCount = 0; nCount < 10; nCount++) MethodTwo();
}
public void MethodTwo()
{
   // Can I retrieve here information about the call to MethodOne which originated this call?
}

For example, in this situation I would like to be able to know at runtime that a given set of ten calls to MethodTwo were originated from a call to MethodOne in a given thread... Is this possible?

Upvotes: 2

Views: 517

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062502

This is horrible:

string caller0 = new StackFrame(1).GetMethod().Name; // MethodOne
string caller1 = new StackFrame(2).GetMethod().Name; // whatever called MethodOne

(this also doesn't come free; any such abuse has a performance price)

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 837926

Not easily, though it is possible if you examine the current stack trace:

using System.Diagnostics;

// ...

StackTrace t = new StackTrace();

If you need your code to behave differently depending on who the caller is, you should have an extra parameter to your method that the caller can use to identify themselves.

If you are using this information to debug your application then you might instead wish to use a profiler that can tell you this sort of information without you having to modify your code.

Upvotes: 1

Related Questions