Ryan Lester
Ryan Lester

Reputation: 2403

Stack trace skipps a method?

I have a class Foo with a method SomeMethod(). In SomeMethod(), I run: Bar bar = new Bar(); bar.BBQ();. Within BBQ(), I call the private method Name(n) which throws an exception with the message new StackTrace().GetFrame(n).GetMethod().Name.

My intention is to pass 1 to Name(n), so that it will return the value "BBQ". However, Name(0) returns "Name" and Name(1) returns "SomeMethod". In the stack trace resulting from the exception being thrown, it also reads as though Name were directly called by SomeMethod (with no mention of BBQ).

Is there a way around this? Does anyone have any idea what could be causing this error? Is there maybe a better way to accomplish getting the value "BBQ" from Name?

[TestClass]
public class Foo
{
    public Foo()
    {
    }
    [TestMethod]
    public void SomeMethod()
    {
        Bar bar = new Bar();
        bar.BBQ();
    }
}

public class Bar
{
    public Bar()
    {
    }
    public void BBQ()
    {
        Name( 1 );
    }
    private void Name( int n )
    {
        throw new Exception( new StackTrace().GetFrame(n).GetMethod().Name );
    }
}

Upvotes: 1

Views: 884

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500785

I strongly suspect the problem is that the method is being inlined by the JIT compiler. You could probably verify this by running a debug build within the debugger, and seeing if that solves the problem.

You can get the immediate calling method relatively easily, but getting a completely accurate stack trace isn't feasible in a non-debugger environment, I believe. You wouldn't want to disable inlining, after all.

Upvotes: 5

Related Questions