Casting/unboxing generic types
<p>Good day,</p>

<p>I have a class that is used to store a value of Type T that I don't know what the type will be until runtime. I want to unbox/cast, not sure what the correct term is, a specific type (in this case a nullable decimal) back to type object.</p>

<p>Please forgive my code layout:</p>

<p>The class snippet:</p>

<pre><code>public abstract class Types
    {
        public class ValueField&lt;T&gt;
        {
            [XmlAttribute]
            public int TemplateID { get; set; }

            [XmlAttribute]
            public int FieldID { get; set; }

            [XmlIgnore]
            [ScriptIgnore]
            public TemplateApprovalField Field { get; set; }

            [XmlIgnore]
            [ScriptIgnore]
            public InstanceTemplateActivityValues Values { get; set; }

            [XmlAttribute]
            public T Value { get; set; }
        }
    }
</code></pre>

<p>The function snippet:</p>

<p>I am stuck at the line "values.Add((Types.ValueField)field);", don't know how to cast it. At that moment, var field is a Types.ValueField.</p>

<pre><code> Values = new Func&lt;XmlDocument, List&lt;Types.ValueField&lt;object&gt;&gt;&gt;(xml =&gt;
 {
  List&lt;Types.ValueField&lt;object&gt;&gt; values = new List&lt;Types.ValueField&lt;object&gt;&gt;();

if (xml != null)
{
  foreach (XmlNode node in xml.SelectNodes("//Field"))
  {

    if (node.Attributes["Type"].Value == "Numeric")
      {
        var field = new Types.ValueField&lt;decimal?&gt;()
        {
          Field = ApprovalFields.Find(f =&gt; f.FieldID == int.Parse(node.Attributes["ID"].Value)),
          FieldID = int.Parse(node.Attributes["ID"].Value),
          TemplateID = int.Parse(node.SelectSingleNode("../@ID").Value)
        };
        field.Value = new Func&lt;string, decimal?&gt;(val =&gt;
          {
            if (string.IsNullOrEmpty(val))
              return null;
            else
            {
              decimal parsed = 0;
              if (decimal.TryParse(val, out parsed))
                return parsed;
            }
            return null;
        })(node.InnerText);


      values.Add((Types.ValueField&lt;object&gt;)field); //This is where my problem occurs...
   }
 }


}
   return values;
   })(row["Form_Values"] != DBNull.Value ? 
      new XmlDocument() { InnerXml =  row["Form_Values"].ToString() } : null)
</code></pre>

<p>Any input will be greatly appreciated.</p>

<p>Regards
YP</p>
