Follow Rinat Abdullin
« MsBuildToCCNetLogger fails on shutdown (MSB4015) | Main | How to Find C# Samples of Lokad Shared Libraries? »
Tuesday
16Dec2008

How to use Linq Expressions to Find Out Variable Name in .NET?

Let's talk C# code:

static void Main(string[] args)
{
  var domain = "matrix";
  Check(() => domain);
  Console.ReadLine();
}

Output:

Name is: 'domain'
Value is: 'matrix'

Implementation:

static void Check<T>(Expression<Func<T>> expr)
{
  var body = ((MemberExpression)expr.Body);
  Console.WriteLine("Name is: {0}", body.Member.Name);
  Console.WriteLine("Value is: {0}", ((FieldInfo)body.Member)
   .GetValue(((ConstantExpression)body.Expression).Value));
}

The original post How to Find Out Variable or Parameter Name in C#? has got updated with more details on this approach (that's the second one).