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.
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:
Otherwise, if
MyMethod
is inlined the stack trace does not contain the frame forMyMethod
which your code may depend on.