views:

126

answers:

4

I need to have an algorithm that can get the object a method within the method like this:

public class Class1 {

    public void Method () {
        //the question
        object a = ...;//the object that called the method (in this case object1)
        //other instructions
    }

}

public class Class2 {

    public Class2 () {
        Class1 myClass1 = new Class1();
        myClass1.Method();
    }

    public static void Main () {
        Class2 object1 = new Class2();
        //...
    }

}

Is there any way to do this?

A: 

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).

Teun D
The issue with this it will can give what called it. Not the instance of the object calling it.
David Basarab
Yes, you are right. The question refers to the instance, so this will not work.
Teun D
+2  A: 

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);
dbemerlin
Encapsulation is a language feature enforced by the compiler. We can break it in all sorts of ways at runtime (for example, using reflection we can modify private fields).
Jason
It's not impossible because it breaks encapsulation (lots of things that are possible do that). It's a *very bad idea* because of that. :-)
T.J. Crowder
Well, i'd rather say "Not possible" than explain "It's not a good idea, because..." and then getting the response "Yeah, yeah, i haven't listened to your stuff on bad style and whatever and my idea sounds cool so i will just do it".
dbemerlin
It doesn't matter what you'd rather say; your answer is premised on a factually incorrect statement.
Jason
Critics accepted and post corrected.
dbemerlin
+1  A: 

or just pass the object as method parameter.

public void Method(object callerObject)
{
..
}

and call the Method:

myClass.Method(this);

regards, Florian

overfloouuu
A: 

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.

used2could