mercredi 19 décembre 2018

C# Set generic property value of primitive type

I am trying to set the value of a primitive type in an generic object dynamically in C#

//Create a new instance of the value object (VO)
var valueObject = Activator.CreateInstance<T>();
//Get the properties of the VO
var props = valueObject.GetType().GetProperties();
//Loop through each property of the VO
foreach (var prop in props)
{
    if (prop.GetType().IsPrimitive)
    {
         var propertyType = prop.PropertyType;
         var value = default(propertyType);
         prop.SetValue(prop, value);
    }
}

The problem being that I cannot use propertyType as a type to get the default value for. How do I get propertyType to a type that can be used by default()?





Aucun commentaire:

Enregistrer un commentaire