Check if any property of class is null

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

This might 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));

Method 3

I use the below extension of the object which I use for validating objects that I don’t want to have all properties null or empty in order to save some calls to the database. I think it fits your case along with some more.

    /// <summary>
    /// Returns true is all the properties of the object are null, empty or "smaller or equal to" zero (for int and double)
    /// </summary>
    /// <param name="obj">Any type of object</param>
    /// <returns></returns>
    public static bool IsObjectEmpty(this object obj)
    {
        if (Object.ReferenceEquals(obj, null))
            return true;

        return obj.GetType().GetProperties()
            .All(x => IsNullOrEmpty(x.GetValue(obj)));
    }

    /// <summary>
    /// Checks if the property value is null, empty or "smaller or equal to" zero (for numeric types)
    /// </summary>
    /// <param name="value">The property value</param>
    /// <returns></returns>
    private static bool IsNullOrEmpty(object value)
    {
        if (Object.ReferenceEquals(value, null))
            return true;

        if (value.GetType().GetTypeInfo().IsClass)
            return value.IsObjectEmpty();

        if (value is string || value is char || value is short)
            return string.IsNullOrEmpty((string) value);

        if (value is int)
            return ((int) value) <= 0;

        if (value is double)
            return ((double) value) <= 0;

        if (value is decimal)
            return ((decimal) value) <= 0;

        if (value is DateTime)
            return false;

        // ........
        // Add all other cases that we may need
        // ........

        if (value is object)
            return value.IsObjectEmpty();

        var type = value.GetType();
        return type.IsValueType
            && Object.Equals(value, Activator.CreateInstance(type));
    }

The call is obviously obj.IsObjectEmpty()

Method 4

I used [Required] annotation from using System.ComponentModel.DataAnnotations for every property, where I want to validate, if it is null.

example:

using System.ComponentModel.DataAnnotations;

public class test
    {
        [Required]
        public string Name { get; set; }

        [Required]
        public int Age{ get; set; }

        public string Sex{ get; set; }

    }

in my example it will validate first two properies.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x