title: How can I dynamically update different fields of a class from inside a method?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/8663919/how-can-i-code-a-c-sharp-function-to-accept-a-variable-number-of-parameters">How can I code a C# function to accept a variable number of parameters?</a>  </p>
  </blockquote>
  
  
  
  <p>I have the following class:</p>
  
  <pre><code>public class Product : AuditableTable  
  {
      public string Position { get; set; }
      public string Quantity { get; set; }
      public double Location { get; set; }
  }
  </code></pre>
  
  <p>What I need is to be able to update fields in the class with the following function. </p>
  
  <p>Parameters:</p>
  
  <ul>
  <li>ac and pr define the keys and enable me to get an instance of the class. </li>
  <li>fld is the field name of the class to update. It could be "Position", "Quantity" or "Location" or ??</li>
  <li>val is the value. It could be something like "London" or "1.234"</li>
  </ul>
  
  <p>How can I arrange for the field name to be set dynamically without using a case statement to 
  check each value of fld and many different setters. Also if there's some way of setting the field
  dynamically how do I deal with casting it to the correct object type for that field?</p>
  
  <pre><code>    public void Update(string ac, string pr, string fld, string val) 
      { 
          try 
          { 
              vm.Product = _product.Get(ac, pr);
              vm.Product. xxx = fld 
          }
          catch (Exception e) { log(e); }
      }
  </code></pre>
  
  <p><strong>Update</strong></p>
  
  <p>Here's the solution proposed by Pieter:</p>
  
  <pre><code>public void Update(string ac, string pr, string fld, string val) { 
              try { 
                  vm.Product = _product.Get("0000" + ac, pr);
                  if (vm.Product != null)
                  {
                      var property = vm.Product.GetType().GetProperty(fld);
                      var type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
                      val = Convert.ChangeType(val, type);
                      property.SetValue(vm.Product, val, null); 
                  } 
                  _product.AddOrUpdate(vm.Product);
              }
              catch (Exception e) { log(e); }
          }
  </code></pre>