Chris Wright Chris Wright - 1 year ago 42
C# Question

Obtaining original variable name from within an extension method

We are currently working on a logging solution and have implemented an extension method call 'Log'. When writing to the log file, we would ideally like to write the original variable name (rather than the variable name used in the extension method).

What we are currently having to do for this is:

public void DoSomeWork()
String testString = "Hey look I'm a string!";
testString.Log("testString value");

With the extention method:

public static String Log(this String valueToStore, String name)
// The logging code which uses the 'name' parameter

The issue here is that it becomes difficult to read on longer lines of code and looks clustered. What would be ideal is this:

public void DoSomeWork()
String testString = "Hey look I'm a string!";

With the extension method:

public static String Log(this String valueToStore)
// The logging code which is able to retrieve the
// value 'testString' from the 'valueToStore' value

Is this at all possible by using Reflection? I'm aware of the
option, but that only returns the string 'valueToStore' when used in the extension method.

Answer Source

You can use an Expression to achieve that, but performance-wise it may not be the best option:

public static void Log<T>(Expression<Func<T>> expr)
    var memberExpr = expr.Body as MemberExpression;

    if (memberExpr == null)

    var varName = memberExpr.Member.Name;
    var varData = expr.Compile()();

    // actual logging


var test = "Foo";
Log(() => test);

Alternatively, if you're using C# 6.0, it can get a bit better using the nameof operator:


A better solution would be one that is leveraging the compiler abilities (specifically, the "Roslyn" compiler) and provide the member name on compile time.