views:

506

answers:

1

All, just wondering if it's possible in .NET/C# to get a list of variables on the stack and their values? I am creating an exception handler for my app and beyond a standard stack trace I'd also like to see the names and values for any variables that are on the stack. Any idea if this can be done?

+2  A: 

Yes, the StackFrame class can help you with that.

Linkage

Something along these lines

var currentStackFrame = new StackFrame(1);
var props = currentStackFrame.GetMethod().GetParameters();
BFree
What? It's true!
BFree
when did a stack overflow become give me the codes plz?
Jimmy
Meh, whatever. That's why I edited it and added the code.
BFree
This will only get the names of the parameters, not the values, and tells you nothing about the other variables on the stack.
Daniel Earwicker
@Jimmy I find if you just link to an article, stack overflow will become: One, Like every other forum on the net where everyone says RTFM and Two its not really helping anyone because most of the time people will come here and ask for code because they have a hard time understanding it.
Nathan W
Yeah with what earwicker said, I don't think this allows you to get any values (although you can get other variables on the stack by looping through each frame on the StackTrace object). Any ideas on how to get the values?
@Earwicker/Alphamacaroon: Could you not use reflection to then extend that sentiment and grab the variable values for each of the variables in the stack?
BenAlabaster
You pretty much need an object instance to get any values using reflection. Not sure where we would get an object instance from the StackFrame or StackTrace method.
I know this should be possible because applications like RedAnt profiler enable you to see variables and their values...
"extend that sentiment" - you mean close my eyes and make a wish?
Daniel Earwicker