SubRoutine Name Variable?

JDYoder

Centurion
Joined
Nov 18, 2003
Messages
144
Is there such a thing as a variable that will give you the name of the subroutine you are in? I see it's tucked in the ex object via ex.ToString and ex.StackTrace.ToString. But I don't want to mess with parsing it out because depending on the error, the location in the string changes. Also, in some cases, it'd be nice to expose the name of the subroutine without have to rely on an error occuring at all.

So does .NET have a variable that contains the name of the subroutine you are in?
 
The following snippet should get you started, the stack frame can also give access to a lot more information than just the method name.

Also the GetFrame call takes a 0 based index with 0 being the current method and 1 being the calling method etc.

C#:
StackTrace st = new StackTrace(0, true);

StackFrame sf = st.GetFrame(0);
MessageBox.Show(sf.GetMethod().Name);
be aware that in a release build run without a debugger attached the results may not accurately reflect the call stack due to method inlining etc.
 
Thanks. I'll try that out. But you're basically saying there's no guarantee this will work for a release build in production?
 
Pretty much it. Various optimisations are performed at runtime one of which is method inlining - this avoids the overhead of a function call by merging a small routine into the calling routine's body.

This means the stack trace for a release build can differ to a debug build.

Try putting the above code into a simple method of it's own and call this method from a form load or button click - try this with a debug build and then try with a release build run without a debugger attached and notice the difference.
 
Why not just create your own variable that tracks the name of the currently executing subroutine?

Private Sub BuildContextMenus()
_executingSub = "BuildContextMenus"

...

End Sub

RappyFood
 
In our error routines, that's essentially what our team is passing in the error message. But when routine names change, sometimes people don't remember to change it. So to prevent coding errors, it'd be nice to just have .NET track it for you.

Also, you can't put it in a modal or global level variable since it would constantly change and very likely not be accurate for when it actually is referred to in an error routine.
 
We're using
System.Reflection.MethodInfo.GetCurrentMethod().Name;

I have no idea how this is influenced by the inlining that PlausiblyDamp describes, but we havent had problems with it yet. *searches for wood*
 
IIRC certain methods under the reflection namespace can prevent inlining - I just can't remember for the life of me where I heard it though...

The main reason I tend to use the stackframe is it can provide more information than just the method name (like the file name for one).
 
Back
Top