Alex Rivera | Logout

How can I get the values of the parameters of a calling method?

Asked 2009-01-29T17:27:50.967
24

Question

I'm writing some code that needs to be able to get the values of the parameters from the method that called into the class. I know how to get all the way to the ParameterInfo[] array, but I don't know how to then get the values. Is this even possible?

If it is, I think it has something to do with using the MethodBody property from the MethodInfo object, which allows you to inspect the IL stream, including properties, but I don't know how to do it, and I haven't found applicable code on Google.

Code

// Finds calling method from class that called into this one
public class SomeClass
{
    public static void FindMethod()
    {
        for (int i = 1; i < frameCount; i++)
        {
            var frame = new StackFrame(i);
            var methodInfo = frame.GetMethod();
            if (methodInfo.DeclaringType != this.GetType())
            {
                string methodName = frame.GetMethod().Name;
                var paramInfos = methodInfo.GetParameters();

                // Now what?? How do I get the values from the paramInfos

                break;
            }
            else if (i == frameCount - 1)
            {
                throw new TransportException("Couldn't find method name");
            }
        }
    }
}
Edit
Report

1 Answer

5

Jonathan Keljo at Microsoft says, in this news group post, :

Unfortunately, the only easy way to get argument information from a callstack today is with a debugger. If you're trying to do this as part of error logging in an application and you plan to send the error log back to your support department, we're hoping to have you use minidumps for that purpose in the future. (Today, using a minidump with managed code is a little problematic as it does not include enough information to even get a stack trace by default. A minidump with heap is better, but not so "mini" if you know what I mean.)

A purist would say that allowing people to write code that can get arguments from functions elsewhere on the callstack would encourage them to break encapsulation and create code that's very fragile in the face of change. (Your scenario does not have this particular problem, but I've heard other requests for this feature that would. Anyway most of those requests can be solved in other ways, like using thread stores.) However, more importantly there would be security implications of this--applications that allow plugins would be at risk of those plugins scraping the stack for sensitive information. We could certainly mark the function as requiring full-trust, but that would make it unusable for pretty much every scenario I've heard of.

Jonathan

So... I guess the short answ

answered 2009-01-29T17:40:48.397

Your Answer