C# Reflection: Get Property Value of Nested Classes

posted in: Uncategorized | 0

So, let’s say I have a set of objects where object B has an instance of object A as one of it’s properties.

public class ObjectB
{
	public int Id { get; set; }
	public string Name { get; set; }
}

public class ObjectA
{
	public int Id { get; set; }
	public string Name { get; set; }
	public ObjectB Child { get; set; }
}

If this was bound to a gridview, I would be able to grab the value of Object A’s Child property using the dot notation.

obj.Child.Name

To grab a property value of ObjectA, I could do something like this…

obj.GetType().GetProperty("Name").GetValue(obj, null);

However, this doesn’t help with my child objects. So, let’s write an extension method using object reflection to do this.

public static class ReflectionHelper
{
	public static Object GetPropValue(this Object obj, String propName)
	{
		string[] nameParts = propName.Split('.');
		if (nameParts.Length == 1)
		{
			return obj.GetType().GetProperty(propName).GetValue(obj, null);
		}

		foreach (String part in nameParts)
		{
			if (obj == null) { return null; }

			Type type = obj.GetType();
			PropertyInfo info = type.GetProperty(part);
			if (info == null) { return null; }

			obj = info.GetValue(obj, null);
		}
		return obj;
	}
}

This method will use the normal method if a normal string is passed, or attempt to parse the string if dot notation is used.

Example usage:

obj.GetPropValue("Child.Name");
My name is Andrew McGivery. I currently work full time as an application developer at Manulife Financial in Canada. My current passion is building and leading highly engaged teams where employee happiness, learning, and growth is a priority.

Leave a Reply