I was wondering…
When I have a code like this:
lock (obj)
{
MyCode.MyAgent();
}
Can MyAgent contain code that recognizes it is running under a lock block?
What about:
for (int i=0;i<5;i++)
{
MyCode.MyAgent();
}
Can MyAgent contain code that recognizes it is running under a loop block ?
The same question can be asked for using blocks, unsafe code , etc… – well you get the idea…
Is this possible in C#?
This is just a theoretical question, I’m not trying to achieve anything… just knowledge.
It isn’t completely impossible, you can use the StackTrace class to get a reference to the caller method and MethodInfo.GetMethodBody() to get the IL of that method.
But you’ll never get this reliable, the just-in-time compiler’s optimizer will give you a very hard time figuring out exactly where the call is located. Method body inlining will make the method disappear completely. Loop unrolling will make it impossible to get any idea about the loop index. The optimizer uses cpu registers to store local variables and method arguments, making it impossible to get a reliable variable value.
Not to mention the tin foil chewing effort involved in decompiling IL. None of this is anywhere near the simplicity and speed of just passing an argument to the method.