.NET - Get default value for a reflected PropertyInfo
Solution 1:
I believe if you just do
prop.SetValue(obj,null,null);
If it's a valuetype, it'll set it to the default value, if it's a reference type, it'll set it to null.
Solution 2:
object defaultValue = type.IsValueType ? Activator.CreateInstance(type) : null;
Solution 3:
The "null" trick will set it to the zero value for the type, which is not necessarily the same as the default for the property. Firstly, if it is a new object, why not just leave it alone? Alternatively, use TypeDescriptor
:
PropertyDescriptor prop = TypeDescriptor.GetProperties(foo)["Bar"];
if (prop.CanResetValue(foo)) prop.ResetValue(foo);
This respects both [DefaultValue]
and the Reset{name}()
patterns (as used by binding and serialization), making it very versatile and re-usable.
If you are doing lots of this, you can also get a performance boost using TypeDescriptor
instead of reflection, by re-using the PropertyDescriptorCollection
and using HyperDescriptor (same code, but much faster than either refletion or raw TypeDescriptor
).