lysergic-acid
lysergic-acid

Reputation: 20050

Is it safe to use the StackTrace class to find the caller of the current method

I would like to know if it is safe to use the following code to determine the name (and possibly more information) about the method or object that called the current executing code:

StackTrace stackTrace = new StackTrace();           // get call stack
StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

More particularly, are there any special/corner cases where accessing the frames would not work or throw exceptions?

I have looked in the MSDN page of StackTrace but found no reference to any possible issues.

Upvotes: 1

Views: 1493

Answers (1)

Martin Liversage
Martin Liversage

Reputation: 106916

Methods may be inlined by the compiler providing a different view compared to what you expect from directly looking at the code . You can use an attribute to make sure that your method is not inlined:

[MethodImpl(MethodImplOptions.NoInlining)]
public void MyMethod() {
  // Get the stack trace.
}

Otherwise, if MyMethod is inlined the stack trace does not contain the frame for MyMethod which your code may depend on.

Upvotes: 3

Related Questions