fhcimolin
fhcimolin

Reputation: 614

C# How to turn all empty lists inside object into null

First of all, i'm aware of the popular advice that you should avoid returning empty lists at all. But as of now, due to a myriad of reasons, i'm met with no other choice but to do just that.

What i'm asking is how do I iterate through the properties of an object (probably through Reflection), take whatever lists I may find and check if it's empty. If so, then turn it into null, otherwise, leave it be.

I'm stuck with the following code, which includes somewhat of a try with Reflection:

private static void IfEmptyListThenNull<T>(T myObject)
{
    foreach (PropertyInfo propertyInfo in myObject.GetType().GetProperties())
    {
        if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
        {
            //How to know if the list i'm checking is empty, and set its value to null
        }
    }
}

Upvotes: 3

Views: 620

Answers (1)

Eugene Chybisov
Eugene Chybisov

Reputation: 1704

This should work for you, just use GetValue method and cast value to IList, then check for emptiness and set this value via SetValue to null.

private static void IfEmptyListThenNull<T>(T myObject)
        {
            foreach (PropertyInfo propertyInfo in myObject.GetType().GetProperties())
            {
                if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
                {
                    if (((IList)propertyInfo.GetValue(myObject, null)).Count == 0)
                    {
                        propertyInfo.SetValue(myObject, null);
                    }
                }
            }
        }

Upvotes: 5

Related Questions