Checking if Object has null in every property

  • A+
Category:Languages

I have class with multiple properties;

public class Employee {     public string TYPE { get; set; }     public int? SOURCE_ID { get; set; }     public string FIRST_NAME { get; set; }             public string LAST_NAME { get; set; }      public List<Department> departmentList { get; set; }     public List<Address> addressList { get; set; }  } 

sometimes this object return me with value in any property say

Employee emp = new Employee(); emp.FIRST_NAME= 'abc'; 

remaining values are null. This is OK

But, How do I check when all values in properties of objects are null

like string.IsNullOrEmpty() for object ?

curretly I am checking like this;

if(emp.FIRST_NAME == null && emp.LAST_NAME == null && emp.TYPE == null && emp.departmentList == null ...) 


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.


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.

Disadvantages

  • Reflection can be quite slow, and in this case it is certainly slower than writing explicit code as you currently do.

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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: