views:

699

answers:

6

Is there a way to use .NET reflection to capture the values of all parameters/local variables?

+2  A: 

Reflection is not used to capture information from the stack. It reads the Assembly.

You might want to take a look at StackTrace

http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx

Good article here:

http://www.codeproject.com/KB/trace/customtracelistener.aspx

Lou Franco
+3  A: 

You could get at this information using the CLR debugging API though it won't be a simple couple of lines to extract it.

Rob Walker
Wim Coenen
A: 

Reflection will tell you the type of parameters that a method has but it won't help discover their values during any particular invocation. Reflection doesn't tell you anything about local variables at all.

You need the sort of APIs that the debugger uses to access this sort of info.

AnthonyWJones
A: 

I dont think this is possible, you can get the method and its parameters by looking at the StackTrace.

System.Diagnostics.StackTrace sTrace = new System.Diagnostics.StackTrace(true);
for (Int32 frameCount = 0; frameCount < sTrace.FrameCount; frameCount++){ 
     System.Diagnostics.StackFrame sFrame = sTrace.GetFrame(frameCount);
     System.Reflection.MethodBase thisMethod = sFrame.GetMethod();
     if (thisMethod == currentMethod){
          if (frameCount + 1 <= sTrace.FrameCount){
               System.Diagnostics.StackFrame prevFrame = sTrace.GetFrame(frameCount + 1);
               System.Reflection.MethodBase prevMethod = prevFrame.GetMethod();
          }
     }
}
RyanFetz
A: 

I don't know how it's possible using reflection, but look at using weaving. SpringFramework.Net allows you to define pointcuts that can intercept method calls. Others probably do it as well.

Here's a link to the "BeforeAdvice" interceptor http://www.springframework.net/docs/1.2.0-M1/reference/html/aop.html#d0e8139

Michael Meadows
A: 

The folks at secondlife suspend scripts and move them between servers. That implies that they have to capture the state of a running script, including the values of variables on the call stack.

Their scripting language runs on mono, an open source implementation of the .NET runtime. I doubt that their solution applies to the regular .NET runtime, but the video of the presentation on how they did it (skip to second half) might still be interesting.

Wim Coenen