3

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
        }
    }
}
fhcimolin
  • 616
  • 1
  • 8
  • 27
  • can you provide sample of data and expected result. – Saif Mar 07 '19 at 17:42
  • 1
    https://stackoverflow.com/questions/1043755/c-sharp-generic-list-t-how-to-get-the-type-of-t shows how to check for list... then calling `.Count` property either through `dynamic` or reflection should not be a problem... – Alexei Levenkov Mar 07 '19 at 17:44
  • 1
    The answer you linked to says “NEVER return null when returning a collection or enumerable. ALWAYS return an empty enumerable/collection ...”; how did you interpret this to mean “avoid returning empty lists”? – Dour High Arch Mar 07 '19 at 18:07
  • @DourHighArch Talk about euphemisms... – fhcimolin Mar 07 '19 at 18:09

1 Answers1

5

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);
                    }
                }
            }
        }
Eugene Chybisov
  • 1,634
  • 2
  • 23
  • 32