title: Generic way to set property values with .NET
body: <p>I have hundreds of properties that need to be set in an object, which is hierarchical by nature and would like a generic way of doing so, is this feasible? One of the driving reasons is for error checking and logging. </p>
  
  <p>In this sample below I am setting ReferenceModelIdentifier to a string</p>
  
  <pre><code>    public override void Execute(MESSAGE message)
      {
          message.MISMOReferenceModelIdentifier= "3.0.0.263.12";
  
          Tasks.Add(new AboutVersionsTask(LoanNumber, LoanState));
          Tasks.Add(new DealSetsTask(LoanNumber, LoanState));
  
          foreach (var task in Tasks)
              using (task)
                  task.Execute(message);
  
          // Were the tasks successful?
          Debug.Assert(message.ABOUT_VERSIONS.ABOUT_VERSION.Count &gt; 0, "ABOUT_VERSION");
          Debug.Assert(message.DEAL_SETS.DEAL_SET.Count &gt; 0, "DEAL_SET");
  
          Log.Info("Finished Execute");
      }
  </code></pre>
  
  <p>and in this sample I am setting ApplicationReceivedDate to another object of type MISMODate </p>
  
  <pre><code>    public override void Execute(MESSAGE message)
      {
          var node = new LOAN_DETAIL();
  
          var con = GetOpenConnection();
          string sql;
          IEnumerable&lt;dynamic&gt; data;
          dynamic first;
  
          if (LoanState == LoanStateEnum.AtClosing)
          {
              //(224) ApplicationReceivedDate
              sql = @"
                  SELECT date ApplicationReceivedDate 
                  FROM   foo (nolock) 
                  WHERE  loannum = @loannum";
  
              data = con.Query&lt;dynamic&gt;(sql, new { loannum = new DbString { Value = LoanNumber, IsFixedLength = true, Length = 15, IsAnsi = true } });
  
              first = data.First();
              node.ApplicationReceivedDate = new MISMODate { TypedValue = first.ApplicationReceivedDate.ToString("yyyy-MM-dd") };
          }
      }
  </code></pre>
  
  <p>What I started out coding was something along the lines of </p>
  
  <pre><code>    protected void SetValue(Object property, Object value)
      {
  
      }
  </code></pre>
  
  <p>and the usage would be </p>
  
  <pre><code>    SetValue(message.MISMOReferenceModelIdentifier, "3.0.0.263.12");
  </code></pre>
  
  <p>EDIT</p>
  
  <p>What I ended up doing was this</p>
  
  <pre><code>    protected void SetValue(object theObject, string theProperty, object theValue)
      {
          try
          {
              var msgInfo = theObject.GetType().GetProperty(theProperty);
              msgInfo.SetValue(theObject, theValue, null);
  
          }
          catch (Exception e)
          {
             Log(e);
          }
      }
  </code></pre>
  
  <p>and usage would be</p>
  
  <pre><code>SetValue(message, "MISMOReferenceModelIdentifier", "3.0.0.263.12");
  </code></pre>
  
  <p>Thank you,
  Stephen</p>