I don't think it's theoretically possible. Think about this scenario:
MyClass a, b;
a = new MyClass();
b = a;
Console.WriteLine("name of b is " + SomeMagicClass.GetVarName(b));
//Should it be "b" or "a"?
I am sure there is a better explanation involving generated MIDL code along the lines of variable name not even being present at runtime.
EDIT Alas I was wrong. Inspired by Jon Skeet's post about Null Reference exception handling and suddenly being reminded about projection there is a way to kinda do that.
Here is complete working codez:
public static class ObjectExtensions {
public static string GetVariableName<T>(this T obj) {
System.Reflection.PropertyInfo[] objGetTypeGetProperties = obj.GetType().GetProperties();
if(objGetTypeGetProperties.Length == 1)
return objGetTypeGetProperties[0].Name;
else
throw new ArgumentException("object must contain one property");
}
}
class Program {
static void Main(string[] args) {
string strName = "sdsd";
Console.WriteLine(new {strName}.GetVariableName());
int intName = 2343;
Console.WriteLine(new { intName }.GetVariableName());
}
}