Reputation: 355
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?
Upvotes: 0
Views: 5153
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
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