jeudi 7 mars 2019

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
        }
    }
}





Aucun commentaire:

Enregistrer un commentaire