0

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()?

Tachyon
  • 2,171
  • 3
  • 22
  • 46
  • 1
    why need to set default value? Primitive has his default value. – Antoine V Dec 19 '18 at 13:31
  • 2
    Possible duplicate of [Programmatic equivalent of default(Type)](https://stackoverflow.com/questions/325426/programmatic-equivalent-of-defaulttype) – nosale Dec 19 '18 at 13:34

1 Answers1

2

You should pass the instance to the SetValue:

prop.SetValue(valueObject, value);

If you want to set the default value, you could use:

var propertyType = prop.PropertyType;
var defaultValue = Activator.CreateInstance(propertyType);
prop.SetValue(valueObject, defaultValue);
Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57