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.
To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .
Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property .
A JavaScript object has properties associated with it. A property of an object can be explained as a variable that is attached to the object. Object properties are basically the same as ordinary JavaScript variables, except for the attachment to objects.
This is possible with a method signature like the following:
private static string GetPropertyName<TModel, TProperty>(Expression<Func<TModel, TProperty>> property)
{
MemberExpression memberExpression = (MemberExpression)property.Body;
return memberExpression.Member.Name;
}
You can call this method without an instance of the customer class:
string propertyName = GetPropertyName((Customer c) => c.ID);
Of course you should add some checks for correct expression types before you cast to MemberExpression
and access memberExpression.Member.Name
.
No, you dont need an instance to decompose the Expression
. Even if the expression expects one, you will never invoke it.
In fact, you do it just like you did in first code snippet.
You would change you code to look like this then:
SomeOtherFunction(ExpressionReader<Customer>.GetString(c => c.ID))
Does that make sense to you?
Alternatively:
Customer c = null; // null intentionally
SomeOtherFunction(ExpressionReader.GetString(() => c.ID));
Still no problem as you are not invoking the expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With