Quantcast
Viewing all articles
Browse latest Browse all 7

Answer by t3chb0t for Generic Null/Empty check for each property of a class

@Adriano Repetti was faster with his list of issues ;-) so I'll just post an alternative soltuion where you can have everyting in only one linq query using the All extension. It will stop as soon as some property doesn't meet the conditions.

Consider changing the name to AllPropertiesValid because with your custom conditions like value <= 0 there is no default solution for all properties and it better shows that it checks the properties of the parameter.

public static bool AllPropertiesValid(object obj){    return !obj.GetType().GetProperties().All(p =>    {        var value = p.GetValue(obj);        if (value == null) { return false; }        if (p.PropertyType == typeof(string))        {            return string.IsNullOrEmpty((string)value);        }        if (p.PropertyType == typeof(int))        {            return ((int)value <= 0);        }        if (p.PropertyType == typeof(bool))        {            return (!(bool)value);        }        if (p.PropertyType == typeof(Guid))        {            return ((Guid)value) == Guid.Empty;        }        return true;    });}

(I hope I got the conditions right)


Viewing all articles
Browse latest Browse all 7

Trending Articles