Is there any way via System.Reflection, System.Diagnostics or other to get a reference to the actual instance that is calling a static method without passing it in to the method itself.
For example, something along these lines
class A
{
public void DoSomething()
{
StaticClass.ExecuteMethod();
}
}
class B
{
public void DoSomething()
{
SomeOtherClass.ExecuteMethod();
}
}
public class SomeOtherClass
{
public static void ExecuteMethod()
{
// returns an instance of A if called from class A
// or an instance of B if called from class B
object caller = getCallingInstance();
}
}
I can get the type using System.Diagnostics.StackTrace.GetFrames, but is there any way to get a reference to the actual instance??
EDIT:
I am aware of the issues with reflection and performance, as well as static to static calls, and that this is generally, perhaps even almost univerally, not the right way to approach this. Part of the reason question is I was curious if it was doable, we are currently passing the instance in.
ExecuteMethod(instance)
and just wondered if this was possible and still being able to access the instance.
ExecuteMethod()
@Steve Cooper: I hadn't considered extension methods. Some variation of that might work. I'll play around with that a bit.