Check for null class properties

I have the following class: -

public class Requirements { public string EventMessageUId { get; set; } public string ProjectId { get; set; } public List<Message> Message { get; set; } } 

I compile it using Json: -

 Requirements objRequirement = JsonObject.ToObject<Requirements>(); 

I wanted to check if any property of the class has any value or if null remained after the previous comparison.

For this I tried: -

 bool isNull= objRequirement.GetType().GetProperties().All(p => p != null); 

But during debugging, I found that the property was Null or not every time it gave true.

Please help me how I can achieve this in the Avoioding For/foreach .

+5
source share
2 answers

You check if the properties themselves are null (which will never be true), and not the values โ€‹โ€‹of the properties. Use this instead:

 bool isNull = objRequirement.GetType().GetProperties() .All(p => p.GetValue(objRequirement) != null); 
+12
source

It can do the trick for you.

 objRequirement.GetType().GetProperties() .Where(pi => pi.GetValue(objRequirement) is string) .Select(pi => (string) pi.GetValue(objRequirement)) .Any(value => String.IsNullOrEmpty(value)); 
+2
source

Source: https://habr.com/ru/post/1261683/


All Articles