I am looking for an algorithm that can get the object that called the method, within that method.
For instance:
public class Class1 {
public void Me
Here's an example of how to do this...
...
using System.Diagnostics;
...
public class MyClass
{
/*...*/
//default level of two, will be 2 levels up from the GetCaller function.
private static string GetCaller(int level = 2)
{
var m = new StackTrace().GetFrame(level).GetMethod();
// .Name is the name only, .FullName includes the namespace
var className = m.DeclaringType.FullName;
//the method/function name you are looking for.
var methodName = m.Name;
//returns a composite of the namespace, class and method name.
return className + "->" + methodName;
}
public void DoSomething() {
//get the name of the class/method that called me.
var whoCalledMe = GetCaller();
//...
}
/*...*/
}
Posting this, because it took me a while to find what I was looking for myself. I'm using it in some static logger methods...
You could get to the current stack trace in code and walk up one step. http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx
But as was commented below, this will get you the method and class calling you, but not the instance (if there is one, could be a static of course).
It would be very bad style since
a) that would break encapsulation
b) it's impossible to know the type of the calling object at compile-time so whatever you do with the object later, it will propably not work.
c) it would be easier/better if you'd just pass the object to the constructor or the method, like:
Class1 c1 = new Class1(object1);
or just pass the object as method parameter.
public void Method(object callerObject)
{
..
}
and call the Method:
myClass.Method(this);
regards, Florian
Obviously i don't know the exact details of your situation but this really seems like you need to rethink your structure a bit.
This could easily be done if proper inheritance is structured.
Consider looking into an abstract class and classes that inherit from said abstract class. You might even be able to accomplish the same thing with interfaces.