Accepted answer

First off, if you want to get the value of CustomerAddress.City, you will never get it. CustomerAddress is the type, not the property name. You want to get Address.City.

That said, your GetPropertyValue is not set up to do what you want.

Try splitting the name by the dots:

var propertyNames = property.split('.');

Now, you have a list of the property names {"Address", "City"}

Then, you can loop through these property names, one by one, calling GetPropertyValue recursively.

That should do it :)


@Michael -> the inverted part;-)

public static void SetNestedPropertyValue(object obj, string property,object value)
            if (obj == null)
                throw new ArgumentNullException("obj");

            if (string.IsNullOrEmpty(property))
                throw new ArgumentNullException("property");

            var propertyNames = property.Split('.');

            foreach (var p in propertyNames)

                Type type = obj.GetType();
                PropertyInfo info = type.GetProperty(p);
                if (info != null)
                    info.SetValue(obj, value);


            throw new KeyNotFoundException("Nested property could not be found.");

Related Articles