0

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?

It'sNotALie.
  • 22,289
  • 12
  • 68
  • 103
Fco
  • 195
  • 1
  • 2
  • 13
  • No; that will throw an exception. You need to parse the string and loop through the properties by hand. – SLaks Aug 08 '13 at 14:51
  • You can look at this post: [Nested property](http://stackoverflow.com/questions/1954746/using-reflection-in-c-sharp-to-get-properties-of-a-nested-object). It has the solution you need. – FelProNet Aug 08 '13 at 15:02

2 Answers2

0

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!

beastieboy
  • 833
  • 8
  • 15
0

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;
    }
oakio
  • 1,868
  • 1
  • 14
  • 21