6

Printing the stack trace is not so difficult when using System.Diagnostics. I am wondering if it is possible to print the VALUES of the parameters passed to each method up the stack trace, and if not why not.

Here is my preliminary code:

public static class CallStackTracker
{
    public static void Print()
    {
        var st = new StackTrace();
        for (int i = 0; i < st.FrameCount; i++)
        {
            var frame = st.GetFrame(i);
            var mb = frame.GetMethod();
            var parameters = mb.GetParameters();
            foreach (var p in parameters)
            {
                // Stuff probably goes here, but is there another way?
            }
        }
    }
}

Thanks in advance.

user420667
  • 6,552
  • 15
  • 51
  • 83
  • It won't work: `MethodInfo.GetParameters` returns the declared parameters, not the argument values... – Thomas Levesque Apr 11 '12 at 22:04
  • @ThomasLevesque: Ok, so this particular appraoch may not work. Is there another that will? – user420667 Apr 11 '12 at 22:07
  • Only a debugger has a shot at the necessary info, available from the .pdb file. That however goes down fast from there, a program cannot debug itself and the info is only accurate for the Debug build. Optimizing method calls is a very important jitter optimizer target. You can't make this work. – Hans Passant Apr 11 '12 at 23:25
  • @HansPassant: What is it I can't make work? I'm not sure where you got that I was attempting to optimize anything. – user420667 Apr 12 '12 at 17:18

1 Answers1

2

You can't do that, at least not with the classes provided by System.Diagnostics. The StackFrame class doesn't provide a way to access the argument values (MethodBase.GetParameters provides information about the declared parameters, e.g. their names and types, but not the values of the actual arguments)

I think it's possible to do it with the CLR debugging APIs, but probably not from C#

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758