Get property name

Is there a way to get the property name of the value that was passed to the function?

+3
source share
3 answers

You ask, is this possible?

public void PrintPropertyName(int value) {
    Console.WriteLine(someMagicCodeThatPrintsThePropertyName);
}

// x is SomeClass having a property named SomeNumber
PrintInteger(x => x.SomeNumber);

and "SomeNumber" will be printed on the console?

If yes, then no. This is clearly impossible (hint: what is happening on PrintPropertyName(5)?). But you can do it:

public static string GetPropertyName<TSource, TProperty>(this Expression<Func<TSource, TProperty>> expression) {
    Contract.Requires<ArgumentNullException>(expression != null);
    Contract.Ensures(Contract.Result<string>() != null);
    PropertyInfo propertyInfo = GetPropertyInfo(expression);
    return propertyInfo.Name;
}

public static PropertyInfo GetPropertyInfo<TSource, TProperty>(this Expression<Func<TSource, TProperty>> expression) {
    Contract.Requires<ArgumentNullException>(expression != null);
    Contract.Ensures(Contract.Result<PropertyInfo>() != null);
    var memberExpression = expression.Body as MemberExpression;
    Guard.Against<ArgumentException>(memberExpression == null, "Expression does not represent a member expression.");
    var propertyInfo = memberExpression.Member as PropertyInfo;
    Guard.Against<ArgumentException>(propertyInfo == null, "Expression does not represent a property expression.");
    Type type = typeof(TSource);
    Guard.Against<ArgumentException>(type != propertyInfo.ReflectedType && type.IsSubclassOf(propertyInfo.ReflectedType));
    return propertyInfo;
}

Using:

string s = GetPropertyName((SomeClass x) => x.SomeNumber);
Console.WriteLine(s);

and now "SomeNumber" will be printed on the console.

+5
source

Only if you use lambda, Ie

SomeMethod(()=>someObj.PropName);

(a having method takes a typed expression tree instead of a value)

, . , . .

+5

No. The property will be evaluated before the function is called, and the actual value in the function will be a copy of this value, not the property itself.

+2
source

Source: https://habr.com/ru/post/1773087/


All Articles