Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if any property of class is null

Tags:

c#

.net

asp.net

I have following class:-

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

I am mapping it with incomming Json:-

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

I wanted to check if any property of class has no value or left null after above mapping.

For this I tried :-

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

But while debugging I found that whether property left Null or not each time it gives value true.

Please help me how can I achieve this by Avoioding For/foreach loop.

like image 933
C Sharper Avatar asked Dec 22 '16 04:12

C Sharper


People also ask

How do you check if all fields of an object are null in Java?

In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator. Let's take an example to understand how we can use the isNull() method or comparison operator for null check of Java object.

What is property of null?

null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant.

How check object is empty or not in C#?

C# | IsNullOrEmpty() Method In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.


1 Answers

You're checking if the properties themselves are null (which will never be true), not the values of the properties. Use this instead:

bool isNull = objRequirement.GetType().GetProperties()
                            .All(p => p.GetValue(objRequirement) != null);
like image 122
Rob Avatar answered Oct 12 '22 15:10

Rob