title: Set Object null if all its properties are null in C#
body: <p>I want to write a function which it turns every properies and child properties of an object. And if all properties of one property are null, then I will set that property as null. I will explain with one example.</p>
  
  <p>For example, if both <code>TeacherName</code> and <code>TeacherSurname</code> are null then I want to set <code>Teacher</code> to null. Then, if <code>ExamMark</code> and <code>ExamName</code> and <code>Teacher</code> are null, then <code>Exam</code> will be null.</p>
  
  <p>You can see json version of like my question from this link <a href="https://stackoverflow.com/questions/51990488/javascript-set-object-null-if-all-its-properties-are-null">Json Version</a></p>
  
  <pre><code>public class Student
  {
      public string Name { get; set; }
      public string Surname { get; set; }
      public Address Address { get; set; }
      public Exam Exam { get; set; }
  }
  
  public class Exam
  {
      public string ExamMark { get; set; }
      public string ExamName { get; set; }
      public Teacher Teacher { get; set; }
  }
  
  public class Teacher
  {
      public string TeacherName { get; set; }
      public string TeacherSurname { get; set; }
  }
  
  public class Address
  {
      public string Country { get; set; }
      public string City { get; set; }
  
  }
  </code></pre>
  
  <p><strong>I wrote this method. But this doing only first step. But I need recursive for child class. How can I convert this method to recursive?</strong></p>
  
  <pre><code>public static object ConvertToNull(object obj)
  {
      Type objType = obj.GetType();
      PropertyInfo[] properties = objType.GetProperties();
  
      var mainClassProperties = properties.Where(p =&gt; p.PropertyType.Assembly == objType.Assembly);
  
      foreach (var mainClassProperty in mainClassProperties)
      {
         object propValue = mainClassProperty.GetValue(obj, null);
         var classAllProperties = propValue.GetType().GetProperties();
  
         if (propValue.GetType().GetProperties().All(propertyInfo =&gt; propertyInfo.GetValue(propValue) == null))
         {
             mainClassProperty.SetValue(obj, null);
         }
     }
      return obj;
  }
  </code></pre>