I blogged here about how you can use the System.Diagnostics.StackTrace class to get a stack trace of your current thread. However, you can't use this to get current locals. Ideally, we'd have a method like:
Pair<string, object> StackFrame.GetLocals()
Which would return a managed array of the parameters and local variables and their names for the current frame. It turns out a lot of people have asked us for this. We may add this in some future version. There are a lot of open issues, such as:
- does it give you locals? or just parameters?
- what about variables that get optimized away?
- variable names are currently stored in the pdb. Do we try and load the pdb? Or pull local names into the metadata? (We already have this problem with line numbers in stack traces today)
- do we need a mechanism to give L-values?
- does it give you variables for inlined frames that got folded into the current frame?
Could you use the debugging API?
The debugging inspection API gives you this ability (ICorDebugValue), but you can't debug yourself, so it's tough to use here. If you were truly desperate, you could CreateProcess to spawn a debugger to attach to you, collect this information, pass it on to the debuggee, and then detach. I definitely don't recommend that solution, but mention it for completeness' sake.