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

image

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­gested 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();
}

Lim­i­ta­tions

There are some impor­tant lim­i­ta­tions you need to con­sider when using the Stack Track, these are dis­cussed in more details in the sec­ond post I’ve included 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­piler 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 included in the release package.

Ref­er­ences:

Get­ting the Cur­rent Stack Trace

Caveats about System.Diagnostics.StackTrace

JIT Opti­miza­tion: Inlining

Share

Leave a Reply