A string representation of an object instance property can be taken with Expression<Func<T>>
:
string propertyName = ((MemberExpression) property.Body).Member.Name;
But what if I don't have (don't want to create) the instance? How do I get the property name in this case?
Explained
I need a string representation of a property name of some object.
Let's say there is an entity
public class Customer
{
public int ID;
public string Name;
}
Now I want to pass the key expression of this entity to some other function, thus I need the string "ID", but I don't want to hardcode the string like SomeOtherFunction("ID")
, instead I use the expression SomeOtherFunction(ExpressionReader.GetString(() => CustomerInstance.ID))
. For this to work I need to supply the entity instance.
Now I want to do the same without creating the instance.