Using reflection in C# to get properties of a nested object

I use following method to get the values from (nested classes) properties like

"Property"

"Address.Street"

"Address.Country.Name"

    public static object GetPropertyValue(object src, string propName)
    {
        if (src == null) throw new ArgumentException("Value cannot be null.", "src");
        if (propName == null) throw new ArgumentException("Value cannot be null.", "propName");

        if(propName.Contains("."))//complex type nested
        {
            var temp = propName.Split(new char[] { '.' }, 2);
            return GetPropertyValue(GetPropertyValue(src, temp[0]), temp[1]);
        }
        else
        {
            var prop = src.GetType().GetProperty(propName);
            return prop != null ? prop.GetValue(src, null) : null;
        }
    }

Here is the Fiddle: https://dotnetfiddle.net/PvKRH0


I know I'm a bit late to the party, and as others said, your implementation is fine
...for simple use cases.
However, I've developed a library that solves exactly that use case, Pather.CSharp.
It is also available as Nuget Package.

Its main class is Resolver with its Resolve method.
You pass it an object and the property path, and it will return the desired value.

Invoice inv = GetDesiredInvoice();  // magic method to get an invoice
var resolver = new Resolver();
object result = resolver.Resolve(inv, "BillTo.Address");

But it can also resolve more complex property paths, including array and dictionary access.
So, for example, if your Customer had multiple addresses

public class Customer {
    public String Name { get; set; }
    public IEnumerable<String> Addresses { get; set; }
}

you could access the second one using Addresses[1].

Invoice inv = GetDesiredInvoice();  // magic method to get an invoice
var resolver = new Resolver();
object result = resolver.Resolve(inv, "BillTo.Addresses[1]");

I actually think your logic is fine. Personally, I would probably change it around so you pass the object as the first parameter (which is more inline with PropertyInfo.GetValue, so less surprising).

I also would probably call it something more like GetNestedPropertyValue, to make it obvious that it searches down the property stack.

Tags:

C#

Reflection