0

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

Tal
  • 337
  • 2
  • 8
  • 21

2 Answers2

6

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).

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • 2
    With reflection i'd use a method rather than a property to indicate that it's not trivial. But imo the manual approach is much better anyway. However, i'd use a different name which is more meaningful and more flexible like `IsInitialized`. – Tim Schmelter Jan 28 '15 at 08:24
  • @TimSchmelter: Agree with you Tim. Updated. – Patrick Hofman Jan 28 '15 at 08:39
0
    //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);
Rahul Modi
  • 748
  • 11
  • 21