Make use of the stack trace

As you’re debug­ging and step­ping through your code in Visu­al Stu­dio, you will no doubt have come across the Call Stack win­dow in Visu­al Stu­dio:


You can get access to the same stack trace infor­ma­tion using the Stack­Trace and Stack­Frame class and this opens up some inter­est­ing pos­si­bil­i­ties. For instance, you can have a Log method which can work out the caller method name as sug­gest­ed in this blog post.

You can find the caller method using the fol­low­ing code:

StackFrame frame = new StackFrame(1);
MethodBase method = frame.GetMethod();

With infor­ma­tion about the caller method in hand you can even do inter­est­ing things such as restrict­ing a method so it’s only callable from par­tic­u­lar class or method:

if (method.DeclaringType != typeof(MyClass) || !method.Name.Equals("Mymethod"))
    throw new Exception();


There are some impor­tant lim­i­ta­tions you need to con­sid­er when using the Stack Track, these are dis­cussed in more details in the sec­ond post I’ve includ­ed in the ‘Ref­er­ences’ sec­tion. In short, it’s not guar­an­teed to give you the result you’d expect as result of com­pil­er opti­miza­tion when you make a Release build. And you require infor­ma­tion from the source file such as the line num­ber, etc. you will need to gen­er­ate the sym­bols (.pdb file) and make sure it’s includ­ed in the release pack­age.


Get­ting the Cur­rent Stack Trace

Caveats about System.Diagnostics.StackTrace

JIT Opti­miza­tion: Inlin­ing