Dan Tao
Dan Tao

Reputation: 128447

Is it possible to access the line of code where a method is called from within that method?

Disclaimers:

That said... is this possible? I'm really just curious to know.

In other words, if I have something like this:

int i = GetSomeInteger();

Is there any way from within GetSomeInteger that the code could be "aware of" the fact that it's being called in an assignment to the variable i?

Again: no interest in doing this in any sort of real scenario. Just curious!

Upvotes: 0

Views: 145

Answers (2)

Jeff Schumacher
Jeff Schumacher

Reputation: 3156

It's possible using System.Diagnostics.StackTrace.

For instance, you can get the name of the calling method like so:

    private static void stackExample()
    {
        var stack = new System.Diagnostics.StackTrace(true); // pass true to get more stack info

        var callingMethod = stack.GetFrame(1).GetMethod().Name;
        var callingLine = stack.GetFrame(1).GetFileLineNumber();

        Console.WriteLine("callingMethod: " + callingMethod + " on line " + callingLine.ToString());
    }

http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx

This will not give you the line of code of the calling method, you'll have to have access to the source code for that. stack.GetFrame(1).GetFileName() will give you the filename of the source code containing the method. What you can do from here, with the Method info and line number is to open the source file and get the line of code in question.

GetMethod() gives you all sorts of great information, like which module the method exists in, then from there you can get the assembly information.

It's actually pretty fun to search through all of the metadata, it tells you all kinds of cool stuff about your code.

The reason you cannot get the actual line of code is the source itself in C# form is not stored in the assembly. While you can get the IL, it's a little more difficult to read. :)

Upvotes: 2

Wyatt
Wyatt

Reputation: 1366

I don't know specifically how one would access it, but theoretically, if the code is compiled with debug symbols (like, in the debug configuration) then the information is there.

Upvotes: 0

Related Questions