Search code examples
c#linqsystem.reflection

Get ALL string properties nested within Wrapper class C#


I've been banging my head against the wall trying to figure out how to dynamically traverse an object hierarchy to find ALL string properties under a parent class and do a replace on those strings.

Let's say I have a parent "wrapper" class with some properties. Like so

public class ParentWrapper
{
    public Person Mom { get; set; }
    public Person Dad { get; set; }
    public IEnumerable<Person> Children { get; set; }
    public Person FavoritePerson { get; set; }
    public string FamilyName { get; set; }
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

I want to be able to dynamically use reflection to find ALL string properties that are inside ParentWrapper or any other object. I want to find the string property "FamilyName" that is in the parent class, but I also want to find all of the string values inside the nested classes. I would want to find all the strings for FirstName and LastName for each person and any strings inside objects nested in child classes.

.GetType().GetProperties().Where(prop => prop.PropertyType == typeof(string))

This would get me all of the string properties inside the ParentWrapper class but I want to be able to dynamically drill down to all the different levels.

Hopefully, my request makes sense.


Solution

  • I can not check it right now but i think u could do somethin recursive here like:

    private static void ReadPropertiesRecursive(Type type)
        {
            foreach (PropertyInfo property in type.GetProperties())
            {
                if (property.PropertyType == typeof(string))
                {
                    var FamilyName = property.GetValue(property))// something like this
                    //do what u want with searched values
                }
                if (property.PropertyType.IsClass)
                {
                    ReadPropertiesRecursive(property.PropertyType);
                }
            }
        }