Search code examples
c#propertiesnull-checkisnullorempty

How to check whether all properties of an object are null or empty?


I have an object, lets call it ObjectA, and that object has 10 properties that are all strings.

var myObject = new {Property1="",Property2="",Property3="",Property4="",...}

Is there anyway to check to see whether all these properties are null or empty?

Any built-in method that would return true or false?

If any single of them is not null or empty then the return would be false, and if all of them are empty it should return true.

I'd just like to avoid writing 10 if statements to control for each of the properties being empty or null.


Solution

  • You can do it using Reflection

    bool IsAnyNullOrEmpty(object myObject)
    {
        foreach(PropertyInfo pi in myObject.GetType().GetProperties())
        {
            if(pi.PropertyType == typeof(string))
            {
                string value = (string)pi.GetValue(myObject);
                if(string.IsNullOrEmpty(value))
                {
                    return true;
                }
            }
        }
        return false;
    }
    

    Matthew Watson suggested an alternative using LINQ:

    return myObject.GetType().GetProperties()
        .Where(pi => pi.PropertyType == typeof(string))
        .Select(pi => (string)pi.GetValue(myObject))
        .Any(value => string.IsNullOrEmpty(value));