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.
Something along these lines
var currentStackFrame = new StackFrame(1);
var props = currentStackFrame.GetMethod().GetParameters();
BFree
2008-12-17 22:23:38
What? It's true!
BFree
2008-12-17 22:26:34
when did a stack overflow become give me the codes plz?
Jimmy
2008-12-17 22:34:22
Meh, whatever. That's why I edited it and added the code.
BFree
2008-12-17 22:37:12
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
2008-12-17 22:45:41
@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
2008-12-17 22:47:47
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?
2008-12-17 23:32:05
@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
2008-12-18 00:54:32
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.
2008-12-18 01:35:53
I know this should be possible because applications like RedAnt profiler enable you to see variables and their values...
2008-12-18 01:36:57
"extend that sentiment" - you mean close my eyes and make a wish?
Daniel Earwicker
2008-12-18 17:02:27