Get variable (not hard-coded) name?
.net, declaration, reflection, variables
Solution
Oh there is a simple solution, use expression trees here is an example, just adapt to your needs in c#
string GetPropertyName<T>(Expression<Func<T>> property)
{
MemberExpression ex = (MemberExpression)property.Body;
string propertyName = ex.Member.Name;
return propertyName;
}
Now you can do
String example = null;
String propertyName = GetPropertyName(()=>example.Length);
//propertyName == "Length"
The first time I've seen that, it was a revelation ! ;)
Problem
I am looking for a way to retrieve the variable name, so I don't have to use hard-coded declarations when needed (for property names etc.): I hardly believe it's possible; maybe someone has a solution. Note: even not variables, properties would also be a move. ``` 'Pseudo: Module Module1 Sub Main() Dim variable = "asdf" Dim contact As New Contact Dim v1 = GetVariableName(variable) 'returns variable Dim v2 = GetVariableName(contact.Name) 'returns Name End Sub Class Contact Public ReadOnly Property Name() Get Return Nothing End Get End Property End Class Public Function GetVariableName(variable As Object) As String ':} End Function End Module ``` Answers are welcommed in either VB or C#.