Monday, January 8, 2007

Programmatically accessing the stackt race

Every once in a while I find myself exploring new parts of otherwise well-known namespaces. Some time ago I came across the System.Diagnostics.StackTrace. This is an awesome class that gives you full reflection access to the current stacktrace.
In real life this means that you can programmatically access all the methods that are currently executing leading you to where you are now in your code. Like this, for instance:

System.Diagnostics.StackTrace st=new System.Diagnostics.StackTrace();
for(int i=0;i<st.framecount;i++)

Now, when I first stumbled across this, I instantly had a gut-feeling that this would come in handy some time. First thing that naturally pops into mind is error-handling and logging - but then it occurred to me "hey, you already get the stack-trace when there's an exception".

Somehow I still can't let it totally go - it must be useful for something else - perhaps in an extremely modularized system - or maybe for some advanced unit-testing. Anyone has any ideas?

No comments: