Possible Duplicate:
getting the caller of a method in c#
Is it possible to get the instance of the object that a method is executed from?
For example…
public class Person
{
public string Name { get; set; }
public void PrintMyName()
{
NamePrinter np = new NamePrinter();
np.PrintName();
}
}
public class NamePrinter
{
public void PrintName()
{
Person p = ?;
Console.Writeline(p.Name);
}
}
public class Program
{
static void Main()
{
Person person = new Person() { Name = "Brandon"; }
person.PrintMyName();
}
}
Is there a way to find ‘p’ in the PrintName method?
EDIT: The problem in the above piece of code could be solved lots of different ways and very easily. Please assume I’m not stupid and that this is just the easiest piece of code I could come up with to make my question clear.
You cannot do this because:
When a method in a class is called, nothing about the calling code is pushed onto the stack (other than the method’s arguments) so there is simply no information you can get hold of to use in this way.
The correct solution in your case is, I think, to add a parameter of type Person to PrintName() (which I imagine you’ve already considered?)