Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...