Reflection won't work because, in your example, every call to
GetType
is going to return
System.String
, or whatever the type of the variable is. You're not going to find your variable name on any instance of the
Type
class.
It can be done using an Expression Tree, but this its expensive to execute. Use this code in any case where you have to execute it thousands of times a second and you're going to notice quite the performance hit.
class Program
{
static void Main(string[] args)
{
string Market = string.Empty;
Console.WriteLine(Ext.GetNameOf(() => Market));
}
}
public static class Ext
{
public static string GetNameOf<T>(Expression<Func<T>> expression)
{
var body = (MemberExpression)expression.Body;
return body.Member.Name;
}
}