Click here to Skip to main content
15,896,118 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do I get the name of instance which called that method.

C#
class Program
 {
     static void Main(string[] args)
     {
         Program p1 = new Program();
         Program K1 = new Program();

         K1.Print_InstanceName();
         p1.Print_InstanceName();
     }
     public void Print_InstanceName()
     {
         Console.WriteLine("Object that called this method= "+ /**Get the name of that instance which called this method.**/);
     }


Expected output is like following:

Object that called this method= p1
Object that called this method= K1
Posted
Updated 11-Feb-12 1:10am
v4

1 solution

You can't: what if I do this:
C#
Program p1 = new Program();
Program k1 = p1;

K1.Print_InstanceName();
p1.Print_InstanceName();
What would you expect to print?

In your example, p1 and K1 are not instances to the Program class - they are variables that reference the instances. Objects generally do not have a Name property (controls do) but even if they did, they would not reflect the name that you give to variables in your code.
 
Share this answer
 
Comments
Ratika Agarwal 11-Feb-12 8:01am    
Thanks.But the code I have given here is just an example for the logic that I want. I want to do this operation to check my result. Because I have no other way to check that part of code.
Ratika Agarwal 11-Feb-12 8:08am    
I have 2 Objects of a Class, which are accessing the same set of 4 Methods randomly, which are using the same global variable arrays of that class..
I just want to check whether values of those arrays are affected by those Method Calls or not...!!
OriginalGriff 11-Feb-12 8:20am    
Sorry - could you explain that a bit better - remember I can't see your screen, or read your HDD...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900