C# Extract the local variable name of on an object. Not the generic class name

C# .net 4.5
Visual Studio 2013 Update 3
Windows NT 6.3 build 9200 (Windows 8.1 Home Premium Edition) i586

Looking for a method/process to extract the current local variable name of an object. Not the class name.

The following code example displays the class i.e. Beast, SonOfBeast, GrandSonOfBeast with this.GetType().Name ...but I'm looking for a way to extract the current object name i.e. Monkey, MonkeyJr, MonkeyIII without passing along an ID-tag.

namespace WhoAreYou { class Program { static void Main(string[] args) // Example using Inheritance { Console.WriteLine("~~~~Who is that masked beast~~~~");

        Beast Monkey = new Beast();
        Monkey.Prowl();

        SonOfBeast MonkeyJr = new SonOfBeast();
        MonkeyJr.Prowl();

        GrandSonOfBeast MonkeyIII = new GrandSonOfBeast();
        MonkeyIII.Prowl();

        Console.ReadKey();
    }
}

class SonOfBeast:Beast{ }
class GrandSonOfBeast:SonOfBeast{ }

class Beast
{
    public void Prowl()
    {
        int frequency, duration;
        Console.Write("Your {0} is loose again! ", this.GetType().Name);
        for (int i = 0; i < 3; i++)
        {
            Console.Write(".~.>  ");
            System.Threading.Thread.Sleep(125);    // 0.125 second
            for (int j = 37; j <= 637; j += 300)
            {
                if (j < 637) {frequency = j; duration = 660 - j;}
                else 
                   {frequency = j - 480; duration = j / 2;}
                Console.Beep(frequency, duration);
            }
        }
        Console.WriteLine(); 
    }
}

}

Jon Skeet
people
quotationmark

An object doesn't have a name. A variable has a name, but multiple variables could have values which refer to the same object. For example:

Beast monkey = new Beast();
Beast donkey = monkey;

Now they both refer to the same object - so if there were a way of getting at a name for an object, what would it return? And sometimes there could be no names at all...

If you want an object to have the concept of a name, you should provide it yourself. For example:

public sealed class Beast
{
    private readonly string name;

    public string Name { get { return name; } }

    public Beast(string name)
    {
        this.name = name;
    }
}

Then you could use:

Beast x = new Beast("Monkey");
Console.WriteLine(x.Name); // Prints "Monkey"

people

See more on this question at Stackoverflow