Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to get a variable's name as a string in .NET 4.5? [duplicate]

Possible Duplicate:
get name of a variable or parameter

I want to be able to get a variable's name as a string.

This can be achieved effectively by using a parameterless lambda expression. However, this has a performance overhead, and it's not built-in functionality.

.NET 4.5 has provided CallerMemberNameAttribute to provide a caller's name as a method argument. This gives us a built-in and better (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's name as a string?

As requested, here's a general usage example of what I'd 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

^By better, I mean faster, not requiring reflection, built-into .NET or more elegant, but preferably a combination of these.

like image 990
Sam Avatar asked Oct 31 '12 08:10

Sam


1 Answers

No there is no better/faster way. I think, the expresseion tree way you have linked is the only way to get to the name of the variable.

The CallerMemberNameAttribute, CallerFilePathAttribute, CallerLineNumberAttribute are the sole new features introduced in .NET 4.5 in that area.

like image 67
Jan Avatar answered Oct 30 '22 02:10

Jan