Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16280

How to recursively get properties of a type using reflection?

I need to recursively get all DateTime properties of an object.

Currently I'm doing:

public static void GetDates(this object value)
{
    var properties = value.GetType().GetProperties();

    foreach (var property in properties)
    {
        if (property.GetType().IsClass)
        {
            property.SetDatesToUtc();
        }
        else
        {
            if (property.GetType() == typeof(DateTime))
            {
                //Do something...
            }
        }
    }
}

However, using property.GetType().IsClass is not enough as even strings or date properties are classes.

Is there a way to get properties that are actual classes?

Would it be better if I add an interface to the classes that have DateTime properties and then check if that property implements that interface?

Upvotes: 1

Views: 1309

Answers (2)

pquest
pquest

Reputation: 3290

You are on the right track, but I think your logic is a little reversed. You should be changing date times, and running the same method on everything else:

public static void GetDates(this object value)
{
    if(value == null) //if this object is null, you need to stop
    {
        return;
    }
    var properties = value.GetType().GetProperties();
    foreach(PropertyInfo property in properties)
    {
        //if the property is a datetime, do your conversion
        if(property.GetType() == typeof(DateTime))
        {
            //do your conversion here
        }
        //otherwise get the value of the property and run the same logic on it
        else
        {
            property.GetValue(value).GetDates(); // here is your recursion
        }
    }
}

Upvotes: 1

Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16280

I added an interface to the classes that have a DateTime property. So method changes to:

public static void GetDates(this object value)
{
    var properties = value.GetType().GetProperties();
    foreach (var property in properties)
    {
        if (typeof(IHasDateProperty).IsAssignableFrom(property.PropertyType))
        {
            property.SetDatesToUtc();
        }
        else
        {
            if (property.GetType() == typeof(DateTime))
            {
                //Do something...
            }
        }
    }
}

Upvotes: 0

Related Questions