Checking if Object has null in every property
EDIT
This answer has received some votes in the last time, so I decided to improve it a little, adding simple caching so that ArePropertiesNotNull
does not retrieve the properties every time it is called, but rather only once for every type.
public static class PropertyCache<T>
{
private static readonly Lazy<IReadOnlyCollection<PropertyInfo>> publicPropertiesLazy
= new Lazy<IReadOnlyCollection<PropertyInfo>>(() => typeof(T).GetProperties());
public static IReadOnlyCollection<PropertyInfo> PublicProperties => PropertyCache<T>.publicPropertiesLazy.Value;
}
public static class Extensions
{
public static bool ArePropertiesNotNull<T>(this T obj)
{
return PropertyCache<T>.PublicProperties.All(propertyInfo => propertyInfo.GetValue(obj) != null);
}
}
(Old answer below.)
You could use reflection as proposed by Joel Harkes, e.g. I put together this reusable, ready-to-use extension method
public static bool ArePropertiesNotNull<T>(this T obj)
{
return typeof(T).GetProperties().All(propertyInfo => propertyInfo.GetValue(obj) != null);
}
which can then be called like this
var employee = new Employee();
bool areAllPropertiesNotNull = employee.ArePropertiesNotNull();
And now you can check the areAllPropertiesNotNull
flag which indicates whether all properties are not null. Returns true
if all properties are not null, otherwise false
.
Advantages of this approach
- It doesn't matter whether or not the property type is nullable or not for the check.
- Since above method is generic, you can use it for any type you want and don't have to write boilerplate code for every type you want to check.
- It is more future-proof in case you change the class later. (noted by ispiro).
Disadvantages
- Reflection can be quite slow, and in this case it is certainly slower than writing explicit code as you currently do. Using simple caching (as proposed by Reginald Blue will remove much of that overhead.
In my opinion, the slight performance overhead can be neglected since development time and repetition of code are reduced when using the ArePropertiesNotNull
, but YMMV.
Either you do this by writing down the code to check every property manually (best option) or you use reflection (read more here)
Employee emp = new Employee();
var props = emp.GetType().GetProperties())
foreach(var prop in props)
{
if(prop.GetValue(foo, null) != null) return false;
}
return true;
example from here
Note that int cannot be null! and its default value will be 0. thus its better to check prop == default(int)
than == null
option 3
Another option is to implement INotifyPropertyChanged.
On a change set a boolean field value isDirty
to true and than you only need to check if this value is true to know if any property has been set (even if property was set with null.
Warning: this method every property can still be null but only checks if a setter was called (changing a value).