Is there a better way to get a variable name as a string in .NET 4.5?

Possible duplicate:
get the name of a variable or parameter

I want to get the variable name as a string.

This can be effectively achieved with the help of the immortal lambda expression . However, it has an overhead of performance, and it's not built-in features.

.NET 4.5 provided CallerMemberNameAttribute to specify the caller name as an argument to the method. This gives us the built-in and best (in some cases) way to do this for specific situations.

.NET 4.5 has provided an improvement in this area for a specific context. Is there now also a better ^ means to get any variable name as a string?

As requested, here is a general example of using what I would like to achieve:

 //Assume 'myVariable' is a local variable, member variable, static member variable, constant, parameter or even a property. string myVariableName = ...; //This should get the string name of myVariable 

^ For the better, I mean a faster, reflection-less, embedded .NET or more elegant, but a combination of them is preferable.

+8
reflection c #
source share
1 answer

There is no better / faster way. I think the path of the expression tree you are associated with is the only way to get the variable name.

CallerMemberNameAttribute , CallerFilePathAttribute , CallerLineNumberAttribute are the only new features introduced in .NET 4.5 in this area.

+3
source share

All Articles