title: Accessing child class properties through function in parent class
body: <p>My CTO (<em>Chief Technical Officer</em>) asked me to come up with a way where he could write one single function in the base class, and have access to the all the properties of the child class. Here is what I came up with - </p>
  
  <p><strong>Base Class</strong></p>
  
  <pre><code>class Assets
  {
      public Assets getPropertyVal(Assets asObj)
      {
          PropertyInfo[] propInfos = asObj.GetType().GetProperties();
          string strAttributeValue = "10";
          foreach (PropertyInfo propInfo in propInfos)
          {
              // Getting the value
              var propValue = propInfo.GetValue(asObj, null);
  
              // Setting the value
              propInfo.SetValue(asObj, Convert.ChangeType(strAttributeValue, propInfo.PropertyType), null);
  
          }
          return asObj;
      }
  }
  </code></pre>
  
  <p><strong>Child Class</strong></p>
  
  <pre><code>class House : Assets
  {
      public int rooms{get; set;}
  }
  </code></pre>
  
  <p><strong>Program.cs file</strong></p>
  
  <pre><code>class Program
  {
      static void Main(string[] args)
      {
          House hsObj = new House();
          hsObj.rooms = 5;
  
          Assets asObj = hsObj.getPropertyVal(hsObj);
          // Returns asObj as JSON
      }
  }
  </code></pre>
  
  <p>Now this works fine, but I was just wondering if there was a better way to do this in C#. </p>
  
  <p>Note that <strong>we do not know</strong>  what properties will be present in the child class, so this will have to be determined at run-time.</p>
  
  <p><strong>UPDATE</strong> : <em>Making it clear</em>, I was just wondering if there is a better way to access the child class properties, one without using reflection. The important point to note is that we have no idea what properties a child class may have.</p>
  
  <p><strong>UPDATE #2</strong>  : I am working with a product that has many entities. These entities have different properties. I want to be able to access and work with all these properties in one single place. This function is exactly that. It's that one single place from where I can access all the data.</p>