Disclaimers:
- I am not interested in doing this in any real production code.
- I make no claim that there’s a good reason why I’m interested in doing this.
- I realize that if this is in any way possible, it must involve doing some highly inadvisable things.
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!
It’s possible using System.Diagnostics.StackTrace.
For instance, you can get the name of the calling method like so:
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. 🙂