Tal
Tal

Reputation: 355

Check if all the properties of class are null

I have the following code that should check if all the properties of class are null. I tried the code below but it didn't work. Why? enter image description here

Upvotes: 0

Views: 5153

Answers (2)

Rahul Modi
Rahul Modi

Reputation: 828

    //NameSpace    
    using System.Reflection;

    //Definition
    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;
    }

    //Call
    bool flag = IsAnyNullOrEmpty(objCampaign.Account);

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 156978

You could make a property IsInitialized, that does this internally:

public bool IsInitialized
{
    get
    {
        return this.CellPhone == null && this.Email == null && ...;
    }
}

Then just check the property IsInitialized:

if (myUser == null || myUser.IsInitialized)
{ ... }

Another option is the use of reflection to walk over and check all properties, but it seems overkill to me. Also, this gives you the freedom to deviate from the original design (when you choose all properties, except one should be null for example).

Upvotes: 6

Related Questions