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();
}
}
}
Roslyn.nameofoperator that could potentially be used for this purpose... but even so, you wouldn't be able to use it in the place where you want to use it (the variable name would need to be in scope, soProgram.Mainin your example, notBeast.Prowl). Any in any case, this language feature is not available yet anyway, and there are better ways to do what you want (as suggested in the answers).