Possible Duplicate:
Finding the Variable Name passed to a Function in C#
I would like to get the name of a variable or parameter:
For example if I have:
var myInput = "input";
var nameOfVar = GETNAME(myInput); // ==> nameOfVar should be = myInput
void testName([Type?] myInput)
{
var nameOfParam = GETNAME(myInput); // ==> nameOfParam should be = myInput
}
How can I do it in C#?
Alternatively,
1) Without touching
System.Reflection
namespace,2) The below one can be faster though (from my tests)
You can also extend this for properties of objects (may be with extension methods):
You can cache property values to improve performance further as property names don't change during runtime.
The Expression approach is going to be slower for my taste. To get parameter name and value together in one go see this answer of mine
Pre C# 6.0 solution
You can use this to get a name of any provided member:
To get name of a variable:
To get name of a parameter:
C# 6.0 and higher solution
You can use the nameof operator for parameters, variables and properties alike:
What you are passing to
GETNAME
is the value ofmyInput
, not the definition ofmyInput
itself. The only way to do that is with a lambda expression, for example:and indeed there are examples of that available. However! This reeks of doing something very wrong. I would propose you rethink why you need this. It is almost certainly not a good way of doing it, and forces various overheads (the capture class instance, and the expression tree). Also, it impacts the compiler: without this the compiler might actually have chosen to remove that variable completely (just using the stack without a formal local).