Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 558
Daniel Möller Avatar asked Dec 09 '22 15:12

Daniel Möller


2 Answers

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; }
}
like image 91
I4V Avatar answered Dec 11 '22 07:12

I4V


Not sure what you need but may be it helps you move on.

public class Property<TObj, TProp>
{
    private readonly TObj _instance;
    private readonly PropertyInfo _propInf;

    public Property(TObj o, Expression<Func<TObj, TProp>> expression)
    {
        _propInf = ((PropertyInfo)((MemberExpression)expression.Body).Member);
        _instance = o;
    }

    public TProp Value
    {
        get
        {
            return (TProp)_propInf.GetValue(_instance);
        }
        set
        {
            _propInf.SetValue(_instance, value);
        }
    }
}

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

var user = new User();
var name = new Property<User, string>(user, u => u.Name);
name.Value = "Mehmet";
Console.WriteLine(name.Value == user.Name); // Prints True
like image 35
Mehmet Ataş Avatar answered Dec 11 '22 08:12

Mehmet Ataş