Search code examples
c#reflectionpropertiespropertyinfo

Get Property Info from an object without giving the property name as string


For some reasons, I need to create a Dictionary of PropertyInfo instances corresponding to some class' properties (let's call it EntityClass).

Ok, I could use typeof(EntityClass).GetProperties().

But I also need to determine a value for some specific properties (known at compile time). Normally I could do one of the following:

EntityInstance.PropertyX = Value;
typeof(EntityClass).GetProperty("PropertyX").SetValue(EntityInstance, Value, null);

In order to fill up my dictionary, I need to use PropertyInfo instances instead of just setting the values normally. But I don't feel confortable getting properties by their string names. If some EntityClass changes, it would bring many exceptions instead of compile errors. So, what I ask is:

How to get a known property's PropertyInfo without passing the string name? I would love if there's something just like delegates:

SomeDelegateType MyDelegate = EntityInstance.MethodX;

Ideally:

SomePropertyDelegate MyPropertyDelegate = EntityInstance.PropertyX;

Solution

  • Something like this?

    string s = GetPropertyName<User>( x=> x.Name );
    
    public string GetPropertyName<T>(Expression<Func<T, object>> lambda)
    {
        var member = lambda.Body as MemberExpression;
        var prop = member.Member as PropertyInfo;
        return prop.Name;
    }
    

    or

    public PropertyInfo GetPropertyInfo<T>(Expression<Func<T, object>> lambda)
    {
        var member = lambda.Body as MemberExpression;
        return member.Member as PropertyInfo;
    }
    

    public class User
    {
        public string Name { set; get; }
    }