jeudi 2 mars 2017

How to find values of nested object properties

I have a function that will find properties with empty values on an object and set them to null. This works fine. The problem now is that sometimes there is a nested object and I'm not sure how to iterate through that to do the same logic.

public static T SetEmptyPropertiesNull<T>(T request, Type type)
{
    foreach (PropertyInfo property in type.GetProperties())
    {
        object value = property.GetValue(request, null);

        if (string.IsNullOrWhiteSpace((value ?? string.Empty).ToString()))
            property.SetValue(request, null);
    }

    return request;
}

So for example, say I have a Customer object and on that object I have an Address object. The function I have now will find all of the empty values on the Customer object and convert them to null, but it also needs to find all of the values on the nested Address object and convert them to null. This function can be called for different object types and not all object types will have a nested object. Any ideas?





Aucun commentaire:

Enregistrer un commentaire