Robert
Robert

Reputation: 6226

Get Property Name

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

Upvotes: 3

Views: 1538

Answers (3)

jason
jason

Reputation: 241641

Are you asking if this is 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 to the console?

If so, no. That is clearly impossible (hint: What happens on PrintPropertyName(5)?). But you can do this:

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;
}

Usage:

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

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

Upvotes: 5

Marc Gravell
Marc Gravell

Reputation: 1062790

Only if you use a lambda, I.e.

SomeMethod(()=>someObj.PropName);

(an having the method take a typed expression tree instead of just a value)

However this still takes quite a bit of processing to resolve and involves both reflection and Expression. I would avoid this unless absolutely necessary. It isn't worth learning Expression just for this.

Upvotes: 5

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

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

Upvotes: 2

Related Questions