How to check all properties of an object whether null or empty c#

To check all properties of an object in C# whether they are null or empty, you can use reflection to iterate through each property and check its value. Here’s an example of how you can do it:


    using System;
    using System.Reflection;

    public class MyClass
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public DateTime DateOfBirth { get; set; }
    }

    public class Program
    {
        public static bool AreAllPropertiesNullOrEmpty(object obj)
        {
            if (obj == null)
                return true;

            Type type = obj.GetType();
            PropertyInfo[] properties = type.GetProperties();

            foreach (PropertyInfo property in properties)
            {
                object value = property.GetValue(obj);

                if (value != null)
                {
                    if (property.PropertyType == typeof(string))
                    {
                        if (!string.IsNullOrEmpty((string)value))
                            return false;
                    }
                    else if (property.PropertyType == typeof(DateTime))
                    {
                        if ((DateTime)value != DateTime.MinValue)
                            return false;
                    }
                    // add more property type checks as needed
                }
            }

            return true;
        }

        public static void Main()
        {
            MyClass myObj = new MyClass();
            myObj.Name = "";
            myObj.Age = 0;
            myObj.DateOfBirth = DateTime.MinValue;

            bool arePropertiesNullOrEmpty = AreAllPropertiesNullOrEmpty(myObj);
            Console.WriteLine("Are all properties null or empty: " + arePropertiesNullOrEmpty);
        }
    }
  

In the example above, we have a class MyClass with three properties: Name of type string, Age of type int, and DateOfBirth of type DateTime. The AreAllPropertiesNullOrEmpty method takes an object as a parameter and checks all its properties using reflection. If any property has a non-null value (in the case of string property, it also checks for empty strings), the method returns false. Otherwise, it returns true.

In the Main method, we create an instance of MyClass and set its properties to different values. We then call the AreAllPropertiesNullOrEmpty method passing the object and store the result in the arePropertiesNullOrEmpty variable. Finally, we print the result using Console.WriteLine. In this example, the result will be false because the Name property is an empty string.

You can add additional property type checks inside the foreach loop based on your requirements.

Leave a comment