.GetProperty() can use for log on in property into the property sent?

135 views Asked by At

I'm using this function :

public static Object GetDate(this Object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}

Suppose a sent propName = "Name" and the src is for example 'Person' object. This function works perfect because return the value returned is the value of field 'Name' in 'Person'. But now I need log on into a property inner other property. For Example, propName = "State.Country.Name"

(State and Country are other objects) Then, if I use the function by passing propName = "State.Country.Name" and src = Person (Persona is a object) the function will be returned the name of the Country?

2

There are 2 answers

0
oakio On

This works fine:

    static object GetData(object obj, string propName)
    {
        string[] propertyNames = propName.Split('.');

        foreach (string propertyName in propertyNames)
        {
            string name = propertyName;
            var pi = obj
                .GetType()
                .GetProperties()
                .SingleOrDefault(p => p.Name == name);

            if (pi == null)
            {
                throw new Exception("Property not found");
            }

            obj = pi.GetValue(obj);
        }
        return obj;
    }
0
beastieboy On

Beware, this is untested. I don't remember the correct syntax but you could try:

public static Object GetValue(this Object src)
{
    return src.GetType().GetProperty(src.ToString()).GetValue(src, null);
}

Basically, you are just passing the instance of the property to the extension method - see no property name is passed:

Person p = new Person();
var personCountry = p.State.Country.GetValue();

Hope it works!