title: How to set an object property within a class to a new instance of another class based that object's type?
body: <p>I have the following class (doesn't compile):</p>
  
  <pre><code>public class Field {
      public string fldName { get; set; }
      public object fldValue { get; set; }
      public Field() { }
      public Field(string name, object value) {
          fldName = name;
          Type type = Type.GetType(value);
          fldValue = Activator.CreateInstance(type);
          if (value == null) fldValue = ""; // forces object to be a string
      }
  }
  </code></pre>
  
  <p>I'm trying to get this to work with passing in either a string or another class I created. If I set:</p>
  
  <pre><code>fldValue = value;
  </code></pre>
  
  <p>It only copies the object by reference instead of instantiating a new class. I'm not sure whether I need a generic here or not but would prefer to do without. I'm also unsure of whether or not I need to deep copy the argument object to the new instance object if this code did work.</p>
  
  <p>The properties of the class I want to copy into fldValue besides a string looks like this: </p>
  
  <pre><code> public class DateReminder {
              public DateTime reminderDate {get; set;}
              public bool remindDate { get; set; }
              public int warningTime {get; set;}
              public bool remindWarn { get; set; }
      }
  </code></pre>
  
  <p>For anyone interested, solved by doing the following:</p>
  
  <pre><code> public class Field {
  
          public string fldName { get; set; }
          [XmlElement( typeof(string))]
          [XmlElement(typeof(DateReminder))]
          public object fldValue { get; set; }
  
          public Field() { }
  
          public Field(Field inField) {
              this.fldName = inField.fldName;
              if (inField.fldValue.GetType() == typeof(DateReminder)) {
                  fldValue = (DateReminder)inField.fldValue;
              }
              else fldValue = inField.fldValue;
          }
  
          public Field(string name, object value) {
              if (value == null) {
                  value = "";
              }
              fldName = name;
              fldValue = value;
          }
      }
  </code></pre>
  
  <p>and DateReminder has its own copy constructor.</p>