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?
Asked
Active
Viewed 4,849 times
0

Tal
- 337
- 2
- 8
- 21
-
1`myUser != null`, but `myUser.CellPhone == null`. – Sinatr Jan 28 '15 at 08:09
-
1you are checking class variable for null , not for properties of the class – Kavindu Dodanduwa Jan 28 '15 at 08:09
-
Why did you think this works? – Patrick Hofman Jan 28 '15 at 08:11
-
you need to iterate through all properties of your class http://stackoverflow.com/questions/531384/how-to-loop-through-all-the-properties-of-a-class – Brij Raj Singh - MSFT Jan 28 '15 at 08:11
-
i think this link will help you http://stackoverflow.com/questions/22683040/how-to-check-all-properties-of-an-object-whether-null-or-empty – Rudresha Parameshappa Jan 28 '15 at 08:11
-
1What if a null property is perfectly fine in future? This logic seems to be broken. – Tim Schmelter Jan 28 '15 at 08:15
-
You should include the code text instead of an image. Some users turn off images in their browser, or the image may stop being hosted at which point your question would be `null` – Sayse Jan 28 '15 at 08:31
2 Answers
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
-
2With 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
-
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