I was wondering if there was a simpler way to do something like this?
public int NonNullPropertiesCount(object entity)
{
if (entity == null) throw new ArgumentNullException("A null object was passed in");
int nonNullPropertiesCount = 0;
Type entityType = entity.GetType();
foreach (var property in entityType.GetProperties())
{
if (property.GetValue(entity, null) != null)
nonNullPropertiesCount = nonNullPropertiesCount+ 1;
}
return nonNullPropertiesCount;
}
How about:
(Other answers have combined the “fetch the property value” and “test the result for null”. Obviously that will work – I just like to separate the two bits out a bit more. It’s up to you, of course 🙂