Search code examples
c#methodsstack-tracestack-framegetmethod

Getting The Method That A Method Was Called From?


Is it possible to determine the calling method name "Eat Pizza" in PostError? I guess I could pass "EatPizza" as one of the arguments, but that would require changes each time the method name changes (unnecessary maintenance). But then, I wasn't even able to find the method name "EatPizza" in the context of "EatPizza" (using stacktrace, getframe, getmethod).

public void EatPizza(Pizza p){
    if(p==null){ //A arbitrary made up error
        Utilities.PostError();
    }
    else{
        p.Slices -= 1;
    }
}

...

public void PostError(){
    //Basically posting to database the name of the method
    //Tried this, didn't work: (new StackTrace(true)).GetFrame(5).GetMethod().Name
    //Is it possible to determine the calling method name "Eat Pizza" in this context?
}

When I try different values (0 to StackTrace.FrameCount-1) in StackTrace.GetFrame, I get the following values, when I just want "EatPizza":

.ctor
ThreadStart
Main
_nExecuteAssembly
RunUsersAssemblyDebugInZone

Solution

  • You were on the right track with creating a StackTrace object, but you seem to have misunderstood the argument to GetFrame. Frames are numbered from the bottom-most frame, so:

    • GetFrame(0) would return PostError
    • GetFrame(1) would return the caller of PostError

    So just try this:

    var trace = new StackTrace(true);
    WriteToDB(trace.GetFrame(1).GetMethod().Name);
    

    Personally, I would prefer to get the entire stack trace rather than just the caller, so I'd do this:

    var trace = new StackTrace(true);
    WriteToDB(trace.ToString());